In your readLine function, you return a pointer to the line array (Strictly speaking, a pointer to its first character, but the difference is irrelevant here). Since it's an automatic variable (i.e., it's “on the stack”), the memory is reclaimed when the function returns. You see gibberish because printf has put its own stuff on the stack.
You need to return a dynamically allocated buffer from the function. You already have one, it's lineBuffer; all you have to do is truncate it to the desired length.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
usingnamespace std;
string filter1( string line ); // Use either
string filter2( string line ); // ...
int main()
{
string line;
ifstream infile( "file.txt" );
while ( getline( infile, line ) ) cout << filter2( line ) << '\n';
}
string filter1( string line )
{
string part[3]; // assumes three entities per line
stringstream ss( line ); // set up a stringstream
for ( int i = 0; i < 3; i++ ) getline( ss, part[i], ',' ); // split at commas
part[2] = to_string( stoi( part[2] ) - 1 ); // use stoi to get integer; subtract 1; convert back to string
return part[0] + "," + part[1] + ", " + part[2]; // reassemble string
}
string filter2( string line )
{
int pos = line.find_first_of( "0123456789" ); // locate the number
string part = line.substr( pos ); // grab the number part of the string
part = to_string( stoi( part ) - 1 ); // use stoi to get integer; subtract 1; convert back to string
return line.substr( 0, pos ) + part; // reassemble string
}