如何在 C++ 中从标准输入获取变量输入

How to take variable input from stdin in C++

我试图输入可变数量的字符串和 numbers.Found 这个解决方案 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;
}

但是,当我 运行 代码时,即使我只是按回车键,它也不会从 loop.The 循环中出来,如果只按下回车键,应该终止,但确实如此不会发生。

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

你可以写

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

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