Cin in a while loop

后端 未结 5 966
南笙
南笙 2021-01-25 08:00

So, I\'ve looked around and haven\'t been able to figure out what\'s going on with cin during my While loop. I\'m working through the book C++ Primer (5th edition) and I noticed

5条回答
  •  萌比男神i
    2021-01-25 08:50

    There is an easier way to do this:

    const string hexdigits = "0123456789ABCDEF";
    cout << "Enter a series of numbers between 0 and 15 separated by spaces. Hit ENTER when finished: " << endl;
    string line;
    string result;
    if (getline(cin, line)) // get the whole line
    {
        istringstream iss(result); // break them by spaces
        int i;
        while (iss >> i)
        {
            result += hexdigits[i];
            result += " ";
        }
        cout << "Your hex result:  " << result << endl;
    }
    else
    {
        cout << "Error handling input!" << endl;
    }
    

    With your solution, you would need to press Ctrl-D to end the input.

提交回复
热议问题