I need to read 4 variables from a text file but sometimes the line could have less than 4 values to read from. I need to be able to detect if a line has ended and produce an error message and skip to the next line in the file.
This is some of the bits from the code that I'm looking at. Sorry I'm new to all this I don't know the terminology.
for (int i = 0; i <= numLines; i++)
{
inputFile >> firstValue;
if (inputFile.peek() == '\n')
{
cerr << "ERROR: First value only, ignoring line of the input file";
continue;
}
I thought checking for a '\n' would work but apparently the text files that I'm using done have any '\n', so I'm at a complete loss.
string line;
while(getline(input, line)){
stringstream ss(line);
ss >> a >> b >> c >> d;
if(not ss){
//wrong data type or wrong number of parameters
}
if(not ss.eof()){
//remaining characters
// (¿may you have whitespace at the end? remove them with ss >> std::ws; )
}
}
> I thought checking for a '\n' would work but apparently the text files that I'm using done have any '\n', so I'm at a complete loss.
¿could it be a windows/linux/mac format issue?
Is there any way to check if its the wrong data type and produce an error message for that and separately check if its the wrong number of parameters, AND do it it for each variable in between a b c and d
I have no idea what the problem could be. You've shown some unformatted code with missing semicolons, but I really don't know what to make of it. You need to paste a complete, runnable program for me to see what's actually going on. Preferably in code tags, if you can manage it.
Okay nevermind as far as im aware right now it all works. A couple more questions
1. idk what I did but cout is "ambiguous" now. What could I have possibly changed?
2. Is there anyway to make an error message if there was extra data in the line?
Yes, in the context of a stringstream, eof means "end of line" (i.e., no more data to read from the input, so really the same thing).
Note that I've simplified that test a little bit. It says "if you don't detect eof (after skipping any whitespace from the current position), then there's extra crap on the line".
AHH nevermind its not working still :(
Could there be a problem that the data is coming from a file not cin?
Also the last two variables are strings in my code :/
You would obviously need to show me a runnable example of the problem. How else could I possibly help? The devil's in the details.
But of course it needs to be changed for your strings. I assume you've done that. It's not just going to magically work trying to read strings as ints.
So I broke down the general gist of my program to this and it works so I guess im just missing something in my main program, Ill have to figure it out :(