C++ - 你如何在用户输入后循环?

标签 c++ loops if-statement cin iomanip

在我之前的问题中,我得到了这个答案,如果用户在国家名称中输入超过 5 个字符,它将输出错误。

#include <iostream>
#include <iomanip>

int main()
{
    using namespace std;

    const int maxchar = 5;
    string nationname;

    cout << "What is the name of your nation?" << endl;

    cin >> nationname;

    if (nationname.size() > maxchar)
    {
       cout << "The input is too long." << endl;
       return 1;
    }
}

我想让它在输出错误后循环回到“cout << what is the name...”。

谢谢!

有人在评论中回答了我之前的问题,但我没有让它工作/我不知道如何或在哪里将它放在我的代码中。

最佳答案

while(1){
    cin >> nationname;
    if (nationname.size() <= maxchar)
        break;
    else{
       cout << "The input is too long." << endl;
    }
}

关于C++ - 你如何在用户输入后循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16138585/

相关文章:

c++ - 关于带有复制构造函数的 vs/g++

java - 我的用于输入姓名、年龄以及查看一个人是否年龄足以做某事的 Java 代码有什么问题?

c# - 使用 If "II"检查同一查询的多种可能性

c++ - 如何在 Windows 7 上使用 DirectX 11 和 Visual Studio 2015 工具集 v140

c++ - 在 Windows 窗体中捕获 openCV 视频

php - 如何从数组变量PHP中获取指定列到动态变量中

jquery - MediaWiki Javascript 轮播

c++ - 比较 if 语句中的 3 个参数时无法理解第一个代码的输出

c++ - QWidget 在鼠标按下事件后不响应。

java - 我们如何获得左右子数组总和相同的数组的索引‽