循环直到输入特定字符(C ++)

时间:2017-08-04 09:38:55

标签: c++ loops

我这里有一个小问题。当满足条件时,这部分代码不会中断循环。如果用户输入'N',则应跳过循环,如果用户在每个新循环提示后输入'N',则断开。否则,它是每个输入'Y'的无限循环。

#include <iostream>
using namespace std;

void text();
char text()
{
    char choice;
    cout << "Enter Y/N: " << endl;
    cin >> choice;
    return choice;
}

int main()
{
     text();
     while(text() == 'Y' || text() == 'y') 
     {
         text();
         if(text() == 'N' || text() == 'n') {break;}
     }
system("pause");
return 0;
}

3 个答案:

答案 0 :(得分:1)

代码的问题是你在每次检查中运行text()函数,要求输入,解决方案是将结果从text()存储到另一个变量中,如下所示:

#include <iostream>
using namespace std;

void text();
char text()
{
    char choice;
    cout << "Enter Y/N: " << endl;
    cin >> choice;
    return choice;
}

int main()
{
     char choice;
     choice = text();
     while(choice == 'Y' || choice == 'y') 
     {
         choice = text();
         if(choice == 'N' || choice == 'n') {break;}
     }
system("pause");
return 0;
}

答案 1 :(得分:0)

以下就足够了:

#include <iostream>
int main(){
    char choice = 'y';
    while (std::cin && ::tolower(choice) == 'y'){
        // do work
        std::cout << "Enter Y/N: ";
        std::cin >> choice;
    }
}

如果你坚持使用函数,那么带参数的简单void函数将执行:

#include <iostream>
void choicefn(char& c){
    std::cout << "Enter Y/N: " << std::endl;
    std::cin >> c;
}
int main(){
    char choice = 'y';
    while (std::cin && ::tolower(choice) == 'y'){
        // do work
        choicefn(choice);
    }
}

如果你想变得非常迂腐,那么将while语句修改为:

while (std::cin && ::tolower(choice) == 'y' && ::tolower(choice) != 'n')

答案 2 :(得分:0)

只需将输入的char保存在char变量

char e = text();
   while(e== 'Y' || e== 'y') 
 {
     choice = text();
     if(e== 'N' || e== 'n') 
        break;
 }

同时删除:void text(); 你不能拥有两个具有相同名称的函数,或者可以说,不能重载仅由返回类型区分的函数。