Guys this program is supposed to read names from a textfile then for each name, remove all spaces and delete all characters after the 8th one and output all the results to an output text file with each new name appearing on a fresh line. I am not sure what i have missed. so far the code works but i only get as far as removing spaces and the semicolon. The names in the output file remain the same.
the input textfile has these names:
SS van der Merwe;PJ Ferreira;HW du Plessis;DF Kodisang;AA Papoudopolous;G Mhlanga;TRF Schoeman;LJ Marais-Le Roux;CG Roux;B Nicholaidis;TT Tshabalala;RV Mississipi;
Perhaps you need to output (fout) the substr() instead of the entire string, (hint line 33 is really not doing anything)?
Have you studied string streams yet? This program can be simplified with their use and you could also make use of some of the std::string member functions like std::string.find_first_of().
1 2 3 4 5 6 7 8 9 10 11 12 13 14
...
std::string name;
// Process one "name" at a time. inf is your file stream.
while(getline(inf, name, ';'))
{
size_t pos;
// Remove the spaces from the string. Only looking for spaces or tabs.
while((pos = line.find_first_of(" \t")) != std::string::npos)
line.erase(pos, 1);
// Output the desired substring.
std::cout << line.substr(0,8) << std::endl;
}
...
Have not done string streams yet. but i have modified my code. Now it formats the 1st Name on the text file correctly and prints it to the out out file. but somehow the rest of the names do not get formatted. I think my looping is a bit mixed up. The code now looks as below and yields the result SSVander.
// Find all the semicolons and trim the string before that to a user id with only 8 characters
string String = Name;
for(int i=0; i<String.length(); i++)
if (String[i] == ';');
//write user ids on the textfile
fout << String.substr (0,8) << endl;
// show on the screen the contents of the textfile
cout << String.substr (0,8) << endl;
Your biggest problem is that the way you're trying to read the file you'll only have one string because your file only has one line of text. Since you don't want to give the stringstreams a try then you're going to need to read the file one name at a time using getline(), you'll do this by using the optional third parameter for getline() in a loop to read a string until the semicolon is found.
Instead of trying to do everything in main(), write a function to generate the id from a name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::string name_to_id( std::string name )
{
staticconstexpr std::size_t MAX_ID_SIZE = 8 ;
std::string id ;
for( char c : name ) // for each character in name
{
if( id.size() == MAX_ID_SIZE ) break ; // we got all that we need
elseif( !std::isspace(c) ) id += c ; // not white space; add it to id
}
return id ;
}