Reputation: 1062
I trying out some problems in Google's Code Jam. For the question Store Credit, I have the following code in C++:
if (input.is_open()) {
getline(input, line);
ss << line;
ss >> nCases;
for (int i = 0; i < nCases; i++) {
getline(input, line);
ss << line;
ss >> credit;
cout << credit << endl;
getline(input, line);
ss << line;
ss >> nItems;
cout << nItems << endl;
int list[nItems];
}
input
is text file (everything has been correctly initialised), line
is a string variable to hold the newly extracted line from the text file, while ss
is a stringstream. nCases
, credit
, and nItems
are just int variables. What got me confused is how the extraction operator works as expected when I'm getting nCases
but stopped working once I'm trying to retrieve the value for credit
and nItems
.
Upvotes: 0
Views: 339
Reputation: 803
if these are just integers per line then why not use atoi
if (input.is_open()) {
getline(input, line);
nCases = atoi( line.c_str() );
for (int i = 0; i < nCases; i++) {
getline(input, line);
credit = atoi( line.c_str() );
cout << credit << endl;
getline(input, line);
nItems = atoi( line.c_str() );
cout << nItems << endl;
int list[nItems];
}
Upvotes: 1
Reputation: 91270
Instead of ss << line;
, reset the stream with ss.str(line); ss.clear();
Upvotes: 3