Reading a line of numbers and stopping after the end of the line
Example of input:
I 67 85 49
R 4
D 4
G 65 97
/end input.txt
开发者_JAVA百科So I'm sure this is a elementary programming question but i've been playing with code and tried looking it up in books. But I need a way to keep reading in numbers after the I because theoretically the numbers could be endless. Now the D,G,R I can just code it to read in one number for D and R and two for G because that will never change.
By the way, I stands for Insert, R for Rank, D for delete, and G for Range. It's a program on BSTs. Got most of my code done except for parts of my main and little things here and there.
I was thinking of a while() loop in my switch to do this feat, but I'm pretty I'll have to change up my coding a bit inside the while loop.
I got it working so it reads in the operations perfectly.
Thanks for any suggestions!
Code:
inFile >> oper; //prime the while loop
while(!inFile.eof())
{
switch(oper)
{
case 'I': while(//something to stop at /n)
{
inFile >> value; //tests to see if it
outFile << value; //is working correctly
MainInsert(value);
}
break;
case 'D':
break;
case 'R':
break;
case 'G':
break;
case 'F':
break;
case 'S':
break;
default: outFile << "\n Invalid Operation!" << endl;
exit (0);
}
inFile >> oper;
}
case 'I':
{
std::string str;
std::getline(inFile, str);
std::istringstream iss(str);
iss >> value;
while(iss)
{
outFile << value;
MainInsert(value);
iss >> value;
}
break;
}
Although the solutions suggested by others using std::getline()
method are the best and correct ones, I am suggesting a little change to your code to make it work.
inFile >> oper; //prime the while loop
while(!inFile.eof())
{
switch(oper)
{
case 'I': while(value != '\n')
{
inFile >> value; //tests to see if it
outFile << value; //is working correctly
MainInsert(value);
}
break;
case 'D':
break;
case 'R':
break;
case 'G':
break;
case 'F':
break;
case 'S':
break;
default: outFile << "\n Invalid Operation!" << endl;
exit (0);
}
inFile >> oper;
}
I haven't compiled it but it should work this way.
I tend to prefer performing as much of the parsing as possible before checking the semantics. I would read the complete line at once and then interpret it if possible. In this simple scenario it is possible and the whole parsing can be pushed away from the main block of logic.
std::string line;
while ( getline( in, line ) )
{
// Parse the line:
std::istringstream lin( line ); // process the line
char cmd;
if ( !lin >> cmd ) throw Error; // define your own error: character missing
std::vector<int> args;
std::copy( std::istream_iterator<int>(lin), std::istream_iterator<int>(),
std::back_inserter( args ) );
// Line parsed, interpret:
switch ( cmd ) {
case 'D':
case 'R':
assert( args.size() == 1 ); // ensure there a single argument
// ...
case 'I':
for ( std::vector<int>::const_iterator it = args.begin(), end = args.end();
it != end; ++it ) {
MainInsert( *it );
}
// ...
}
}
精彩评论