How to take variable input from stdin in C++
本问题已经有最佳答案,请猛点这里访问。
我试图输入可变数量的字符串和数字。找到此解决方案链接:
我尝试了这个数字:
1 2 3 4 5 6 7 8 9 | #include<iostream> using namespace std; int main(){ int np; while (cin>>np){ cout << np<<endl; } return 0; } |
对于字符串:
1 2 3 4 5 6 7 8 9 10 | #include<iostream> #include<string> using namespace std; int main(){ string line; while (getline(cin, line)){ cout << line <<endl; } return 0; } |
但是,当我运行代码时,即使我只按Enter也不会退出循环。如果只按Enter键,循环应该终止,但这不会发生。
请提供有关如何实现此功能的建议。
你可以写
1 2 3 | while (std::getline(std::cint, line) && !line.empty()) { // ... } |
仅在获取的字符串为非空时保持循环。