【问题标题】:How to take variable input from stdin in C++ [duplicate]如何在 C++ 中从标准输入获取变量输入 [重复]
【发布时间】:2018-01-24 21:16:55
【问题描述】:

我试图输入可变数量的字符串和数字。找到这个解决方案link

我在 数字 上试过这个:

#include<iostream>
using namespace std;
int main(){
    int np;
    while (cin>>np){
        cout << np<<endl;
    }
    return 0;
}

对于字符串:

#include<iostream>
#include<string>
using namespace std;
int main(){
    string line;
    while (getline(cin, line)){
        cout << line <<endl;
    }
    return 0;
}

但是,当我运行代码时,即使我只是按下回车,它也不会退出循环。如果只是按下回车键,循环应该终止,但这不会发生。

请提供如何实现此功能的建议。

【问题讨论】:

  • 回车键仍然是一个有效的字符串。
  • 那么如果没有其他人,如何停止输入?
  • 取决于操作系统。如果内存可用,在 Windows 中为 Ctrl+Z,在 Unix 中为 Ctrl+D
  • @Abstraction 有些也是Ctrl C
  • 如果您从在线法官那里读取数据,它应该为您设置一个流的结尾。

标签: c++ string stdin getline eof


【解决方案1】:

你可以写

while (std::getline(std::cin, line) && !line.empty()) {
    // ...
}

仅当获取的字符串非空时才继续循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2012-01-25
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多