-1 c++ terminal stdstring is-empty
我找不到一种方法让我的终端在空输入时退出程序。我有:
int main(int argc, char const* argv[]) {
// Write your code here
// Define variables
set<string> words; // The set
bool more = true; // Flag indicating there are more lines to read
// If there is no command line argument, use stdin to get the lines
if (argc == 1){
// Take lines in until a blank line is entered
while (more) {
// Get next line from stdin
string input;
cin >> input;
// Quit if we hit a blank line
if (input.empty() ) {
more = false;
break;
}
Run Code Online (Sandbox Code Playgroud)
我试过了:
if (!cin )
if (input == "")
if (input == "\n")
if (input == "" || "\n")
if (input.empty())
Run Code Online (Sandbox Code Playgroud)
对于每一个,我希望程序不接受任何输入,或者简单地按回车键,作为接受输入的结束并退出。
使用 逐行读取std::getline。如果该行为空,则用户只需按Enter。
您需要在>>按 之前输入一些非空格字符Enter。
另请注意,您当前的输入只会读取单个空格分隔的“单词”,而不是一行。要阅读您真正需要的一行std::getline。
例子:
std::string input;
for (;;)
{
// Try to read a whole line, and check if it's empty or not
if (!std::getline(std::cin, input) || input.empty())
{
// There was an error reading, or there was an EOF,
// or the line was empty (the user just pressed Enter)
break;
}
// TODO: Do something with the input
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30 次 |
| 最近记录: |