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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16138585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:06:26  来源:igfitidea点击:

C++ - How do you loop back after user input?

c++loopsif-statementciniomanip

提问by Leroterr1

In my previous question, I got this answer to work so that if the user inputs more than 5 characters in the nation name, it will output an error.

在我之前的问题中,我得到了这个答案,这样如果用户在国家名称中输入超过 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;
    }
}

I want it so that it will loop back to the "cout << what is the name..." after it outputs the error.

我希望它在输出错误后循环回到“cout << 名称是什么...”。

Thanks!

谢谢!

Someone answered on my previous question how in the comments but I didn't get it to work/I don't know how or where to put it in my code.

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

采纳答案by phoeagon

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

回答by Jerry Coffin

At least to me, the responses you've gotten so far look a little clumsy. IMO, this calls for the little-used, much-neglected do/while loop:

至少对我来说,到目前为止你得到的回应看起来有点笨拙。IMO,这需要很少使用、被忽视的 do/while 循环:

bool show_error() { 
    return std::cout << "The input is too long.\n";
}

int main() { 
    static const int maxchar = 5;
    std::string nationname;

    do { 
        std::cout << "What is the name of your nation?\n";
    } while (std::cin >> nationname && nationname.size() > maxchar && show_error());
}

As to why I think this is better: first of all, unless it's completely unreasonable to do so, it's much better to write the condition for a loop as the loop condition, rather than a while (1)followed by a conditional breaksomewhere inside the loop. Second, if you always want a loop to execute at least once, a do/whileloop is the right one for the job. A whileloop should be used when there's a reasonable chance the loop will not execute at all (when/if the condition is false). Finally, although it's arguably a fairly minor point, this also tests the result of each input and output operation, and breaks out of the loop if either fails. If you don't do that, incorrect input can lead to an infinite loop, where the attempt to read fails, but leaves the data in the input stream, so the next iteration will fail again (without waiting for the user to enter more data).

至于为什么我认为这样更好:首先,除非这样做完全不合理,否则将循环的条件写为循环条件要好得多,而不是在循环内的某处写while (1)一个条件break。其次,如果您总是希望循环至少执行一次,则do/while循环是该工作的正确选择。一种while当有合理的机会循环根本不会执行时(当/如果条件为假)时,应该使用循环。最后,虽然这可以说是一个相当小的点,但这也会测试每个输入和输出操作的结果,如果有一个失败,就会跳出循环。如果不这样做,不正确的输入会导致无限循环,尝试读取失败,但将数据留在输入流中,因此下一次迭代将再次失败(无需等待用户输入更多数据)。

As an aside: I'd advise against using std::endlso much (or probably at all). Get in the habit of using \nwhen you just want a new-line, and std::flushwhen/if you want to flush the stream.

顺便说一句:我建议不要使用std::endl这么多(或可能根本不使用)。养成\n在您只需要换行时使用的习惯,以及std::flush何时/如果您想刷新流。

回答by tausun

add a while loop in your function to continue input when wrong.

在您的函数中添加一个 while 循环以在错误时继续输入。

int main()
    {
        using namespace std;

const int maxchar = 5;
string nationname;

while(1)
{
    cout << "What is the name of your nation?" << endl;

    cin >> nationname;

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

回答by taocp

You basically need a loop to keep asking the user to input new answer when length of input string is too long.

当输入字符串的长度太长时,您基本上需要一个循环来不断要求用户输入新答案。

try the following (following your original logic):

尝试以下操作(遵循您的原始逻辑):

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    const int maxchar = 5;
    string nationname;
    while (true)
    { 
       cout << "What is the name of your nation?" << endl;
       cin >> nationname;
       if (nationname.size() > maxchar)
       {
         cout << "The input is too long." << endl;
         continue;
       }
       else
       {
          cout << "input nation is: " << nationname <<endl;
          break;
       }
   }
   return 0;
}

回答by 4pie0

const int maxchar = 5;
string nationname;

while(!(nationname.size()>0 && nationname.size()<maxchar)){
nationname="";
    cout << "The input has to be smaller than "<<maxchar<<" characters and has"
         <<" to contain at least 1 character."
    cin >> nationname;
}
//nationname is as supposed to be

回答by EniGma

#include "stdafx.h"
#include <iostream>
#include <string>

int main()
{
    //declare a string variable called
nationName

    std::string nationName;


    std::cout << " Please enter youre   
Nation name,\n Names must be no   
longer than 20 characters in 
length\n and must not contain any 
numbers. . ." "\n""\n";

    //Get input from user
    getline(std::cin, nationName);

    //validate the length of the name   
variable, if it is greater than 20   
characters display an error
    while (name.length() >= 20)
    {
        std::cout << " sorry you have  
entered incorect data\n Please try  
again . . . ""\n""\n";

        getline(std::cin, name);
    }
    //if the name is entered correctly
loop exists and displays
    std::cout <<  nationName <<  
std::endl;
    return 0;

}