繁体   English   中英

如何终止从cin读取?

[英]How to terminate reading from cin?

我尝试了这里列出的一堆方法,但没有一个有效。 它总是在等待更多的输入。

我试过while(std::getline(std::cin, line))和下面的方法,似乎没有任何效果:

#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;
      }
}

首先,使用std::cin.eof()来控制你的循环! 它不起作用。 此外,您始终需要在输入检查是否成功输入。

也就是说,要终止输入,您需要输入适当的文件结尾字符,可能在行的开头(它的工作方式完全取决于系统、某些设置等)。 在 Windows 上,您将使用 Ctrl-Z,在 UNIX 上,您将使用 Ctrl-D。

首先,程序的这一部分尝试在堆栈上分配 4 GB 内存,这在我的机器上不起作用(祝你好运找到任何具有 4 GB 连续内存空间的机器):

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

如果我将其更改为更合理的:

long length = 32;

然后它对我来说很好用:

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

所以我猜还有其他问题。


注意:除非您真的计划使用所有这些索引,否则您可能需要考虑使用unordered_map ,因此您只使用您实际需要的空间。

通过将 "std::cin" 评估为布尔值,即while (cin) ,可以最容易地测试您正在寻找的条件。 但它不会这样做,直到您尝试阅读 EOF 之外的内容,因此请期待一个空的 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;
}

现场演示: http : //ideone.com/QR9fpM

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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