I have this code….
file_parser::file_parser(string file){
txtfile.open(file.c_str(), ios::in);
if (!txtfile.good()){
string error=err(0," "+file+" not found. Exit code ",1);
throw file_parse_exception(error);
}
while (!txtfile.eof()){
char str[200];
txtfile.getline(str, 200);
string str2=str;
vfile.push_back(str2);
}
txtfile.close();
}
and the problem is that if I have a line in the input file greater than 200 characters it hangs then crashes. I checked out the value of str at crash and it is preceded by a null char then it tries to push back a null(non-initialized) string onto the vector which causes the hang/crash. does anyone know a way to get around this? I thought by using getline it would truncate the char array at 199(+null) characters but apparently this isn’t happening. I’m stumped. The thing is that I want each pushback to have a max of 200 characters. I really don’t want the WHOLE line which is what ‘string str’ would do. and if a line is over 200 characters it should read the first 200 and then move on to the next line.
Replace your input loop with this:
Using
ios::eof()as a loop condition almost always creates a buggy program, as it did here. In this case, usingeof()has two problems. First,eof()is only set after the read fails, not before, but you are checking it before the read. Second,eof()doesn’t check the range of other errors. When an input line has more than 200 characters,istream::getlinesetsfailbit, but noteofbit.EDIT: With the added requirement of limiting the input lines to 200 characters, this should work: