简体   繁体   中英

How to terminate reading from cin?

I've tried a bunch of methods listed on here but none of them work. It's always waiting for more input.

I've tried while(std::getline(std::cin, line)) and the method below, nothing seems to work:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
  long length = 1UL<<32;
  int array[length];
  // memset(array, 0, (length-1) * sizeof(int));

  for(int i = 0; i < length; i++)
    array[i] = 0;
  string line;
  int num;
  while(!cin.eof()){
    getline(cin,line);
    stringstream ss(line);
    ss >>num;
    array[num]++;
  }
  for(int i = 0; i < length; i++)
      if(array[i]){
          cout << i << ": ";
          cout << array[i] << endl;
      }
}

First off, do not use std::cin.eof() to control your loop! It doesn't work. Also, you always need to check for successful input after the input.

That said, to terminate the input you'll need to enter the appropriate end of file character, probably at the start of the line (how it works entirely somewhat depends on the system, some settings, etc.). On Windows you'd use Ctrl-Z, on UNIXes you'd use Ctrl-D.

First off, this part of your program attempts to allocate 4 GB of memory on the stack, which doesn't work on my machine (good luck finding any machine with 4 GB of continuous memory space):

long length = 1UL<<32;
int array[length];

If I change that to a much more reasonable:

long length = 32;

Then it works fine for me:

$ g++ -g test.cpp -o test && ./test
2
5
# pressed control+d
2: 1
5: 2
$ 

So I'm guessing something else is wrong.


Note: Unless you actually plan to use all of those indexes, you may want to considering using anunordered_map , so you only use the space you actually need.

The condition you are looking for can be most easily tested by evaluating "std::cin" as a bool, ie while (cin) . But it won't do this until you have tried to read beyond EOF, so expect an empty getline:

#include <iostream>
#include <string>

int main() {
    std::string input;
    while (std::cin) {
        std::cout << "Type something in:\n";
        std::getline(std::cin, input);
        if(input.empty())
            continue;
        std::cout << "You typed [" << input << "]\n";
    }
    std::cout << "Our work here is done.\n";

    return 0;
}

Live demo: http://ideone.com/QR9fpM

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