📜  如何在 C++ 中连续输入直到任何值.例如(接受输入直到给出 q) - C++ (1)

📅  最后修改于: 2023-12-03 15:24:08.517000             🧑  作者: Mango

如何在 C++ 中连续输入直到任何值

在 C++ 中,我们经常需要从用户那里获取输入。有时候,我们需要连续获取输入,直到用户输入特定的字符为止。本文将介绍如何在 C++ 中连续输入直到任何值。

使用 while 循环

使用 while 循环可以轻松地实现连续输入,直到用户输入特定的字符。下面是一个示例代码:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input;
    while (cin >> input && input != "q") {
        cout << "You entered: " << input << endl;
    }
    return 0;
}

在这个示例中,输入的字符串会被读取,然后检查是否等于 "q",如果不是,则会输出 "You entered: " 和字符串本身。如果输入等于 "q",while 循环就会停止。

使用 do-while 循环

除了 while 循环之外,您还可以使用 do-while 循环来实现连续输入。下面是一个示例代码:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input;
    do {
        cin >> input;
        cout << "You entered: " << input << endl;
    } while (input != "q");
    return 0;
}

在这个示例中,输入的字符串会被读取,然后检查是否等于 "q",如果不是,则会输出 "You entered: " 和字符串本身。然后,do-while 循环检查输入是否等于 "q",如果是,则停止循环。

总结

本文介绍了如何在 C++ 中连续输入直到任何值。使用 while 循环或 do-while 循环可以轻松实现此功能。无论您选择哪种方法,都请确保您的代码可以正确处理各种输入情况,以避免出现任何异常。