简体   繁体   中英

How to read unknown number of inputs?

I am learning C++ using the book C++ Primer.

In Section 1.4.3 , the following example code about reading the unknown number of inputs is given.

#include <iostream>
int main()
{
  int sum = 0, value = 0;
  // read until end-of-file, calculating a running total of all values read
  while (std::cin >> value)
  sum += value; // equivalent to sum = sum + value
  std::cout << "Sum is: " << sum << std::endl;
  return 0;
}

According to the book, if we give an input of 3 4 5 6 , the output will be Sum is: 18

But when I try this on my computer( Windows 10 with MinGW ), The code does not end. It just keeps on asking for input even if I enter a newline. It works only when I enter a non-int input like f .


Is this expected? If yes, is there any code that stops after inputting a newline?

I am quite new to c++ and I have already learned python, so getting stuck so early on is quite frustrating.


Thanks and regards.

You need to terminate your input by an End-Of-File-character (ie CTRL-Z on Windows, CTRL-D on Mac/Unix), not just by an End-Of-Line (ie Enter ).

A simple Enter is interpreted as white space, which will be simply ignored by operator>> when reading into an integral data type.

CTRL-Z / End-Of-File, in contrast, makes any operator>> fail with an error.

See also this SO answer .

Note: Entering f will also terminate your loop, since f is not considered a valid integral number; Hence, std::cin >> value with value being of type int and an input like f will fail as well. To be more accurate: operator>> actually returns a reference to the input stream, but if reading in a value fails, failbit is set on the stream, and then interpreting the stream object in a boolean expression (implicitly calling basic_istream::operator bool() ) returns false ; So maybe the author of the book did not want to explain these details at the respective section in the book :-)

Is this expected?

Yes , Thats what while (std::cin >> value) does. See this answer for more explanations: How is "std::cin>>value" evaluated in a while loop?

is there any code that stops after inputting a newline?

No , as >> simply ignore a white space(also @StephanLechner mentioned it)

What you can do instead is:

  1. Just give a condition; if it satisfies just break the loop. you can also provide a console out to make it more understandable to the user. For example:

     std::cout << "Enter value to sum or press -1 to exit" << std::endl; while (std::cin >> value && value != -1) // if value == -1, loop stops. { sum += value; } 
  2. You can simply terminate by the end of character:

    • CTRL-Z on Windows
    • CTRL-D on Mac/Unix

Is this expected?

Yes, as operator>> ignores leading whitespace by default, which includes line breaks.

If yes, is there any code that stops after inputting a newline?

Use std::cin.getline() or std::getline() instead of operator>> . You can then use operator>> with a std::istringstream to parse values from each line, eg:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::string line;
    int sum, value;

    do
    {
        std::cout << "Enter a set of numbers, or a blank line to exit: ";
        if (!std::getline(std::cin, line) || line.empty())
            break;

        // read until end-of-line, calculating a running total of all values read
        std::istringstream iss(line);
        sum = 0;
        while (iss >> value)
            sum += value; // equivalent to sum = sum + value

        std::cout << "Sum is: " << sum << std::endl;
    }
    while (true);

    return 0;
}

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM