开发者

Why is the extraction operator not working?

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 e开发者_开发技巧xpected when I'm getting nCases but stopped working once I'm trying to retrieve the value for credit and nItems.


Instead of ss << line;, reset the stream with ss.str(line); ss.clear();


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];
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜