user3777063
user3777063

Reputation:

Reading characters from a line of a file

The first line of my file must be exactly a two digit number which I read into firstline[2]. I use sscanf to read the data from that buffer and store it into an int to represent the number of lines (not including the first one) in the file. If there is a third character I must exit with an error code.

I've tried introducing a new char buffer thirdchar[1] and comparing it to a new line (10 or '\n'). If thirdchar does not equal newline then it should exit with an error code. Later in my program I use sscanf to read firstline and store that number into an int called numberoflines. When I intriduce thirdchar, it appends an extra two zeros to numberoflines to the end of what was in firstline.

//If the first line was "20"
int numberoflines;
char firstline[2];
file.get(firstline[0]);//should be '2'
file.get(firstline[1]);//should be '0'

char thridchar[1];
file.get(thirdchar[0]);//should be '\n'

if (thirdchar !=10){exit();}//10 is the value gdb spits out to represent '\n'

sscanf(firstline, "%d", &numberoflines);//numberoflines should be 20

I debugged this and firstline and thirdchar are the expected values, but numberoflines becomes 2000! I've removed the code related to thirdchar and it works fine, but doesnt meet the requirement of it being a 2 digit number. Am I misunderstanding what sscanf does? Is there a better way to implement this? Thanks.

---------------UPDATE------------------

So I've updated my code to use std::string and std::getline:

std::string firstline;
std::getline(file, firstline);

And I get the following error when trying to print the value of firstline

$1 = Python Exception <class 'gdb.error'> There is no member named _M_dataplus.:

Upvotes: 0

Views: 108

Answers (1)

Nicholas Betsworth
Nicholas Betsworth

Reputation: 1803

sscanf requires the input string to be null-terminated. You are not passing it a null-terminated string so it's not behaving as expected.

As suggested, you would be better placed reading in the string using std::getline and converting the std::string into an integer.

Further reading here if using C++11 onwards, or here otherwise.

Upvotes: 1

Related Questions