Cin in a while loop

后端 未结 5 914
南笙
南笙 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条回答
  • 2021-01-25 08:39

    CTRL-D works on Linux. A simpler code snippet is below:

    vector<double> vd;
    for (double d; cin>> d;)
         vd.push_back(d);
    for(int i=0; i<vd.size(); ++i)
       cout << vd[i] << endl;
    
    0 讨论(0)
  • 2021-01-25 08:43

    Hitting Enter produces either a CR or LF or both, depending on your platform. This is a valid input so satisfies the condition to continue the while loop. You will need to either explicitly test for these characters at the beginning of your input or use Ctrl-C to break out of the loop.

    As a readability issue, I would include braces around the code that you want in the loop. What you have there is valid C++ since without braces the while will loop on the next statement and the whole if conditional is a single statement. Practice putting them in now even on single line loops and you'll save yourself some headache debugging in the future.

    0 讨论(0)
  • 2021-01-25 08:48

    As long as you enter valid numbers it will continue to read numbers. You can terminate the loop by entering something which isn't a number, e.g., "goodbye". At the beginning of a line, i.e., immediately after hitting enter you should also be able to terminate the standard input using Ctrl-Z (I think; I normally work on UNIX-like systems where you'd terminate the standard input using Ctrl-D).

    Essentially, a stream converts to true as long as neither std::ios_base::failbit nor std::ios_base::badbit is set in its state (you can look at stream's state using stream.rdstate()). As long as you successfully read integers from the stream, it has no reason to go into failure state. When you enter something which isn't an integer, it will get std::ios_base::failbit set. Likewise, when it reaches the end of the stream.

    0 讨论(0)
  • 2021-01-25 08:50

    @Protomega, You can use the same code, but press Ctrl+D to stop input stream.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题