1

这个问题之后,我发现使用charas input 将避免由于输入字符而导致的无限循环,而正在使用int. 但现在我遇到了另一个问题。

当我输入下面的代码时:

#include <iostream>
void language();

int main() {
    language();
}

void language() {
    char choice;

    // Ask user for something and input        
    std::cout << "Press 1 to exit the program\n\n";
    std::cin >> choice;

    // Getting user's input and run the code below and find for specific words
    switch(choice) {
        case '1':
            std::cout << "\n\nEnding program...";
            return 0;
            break;
        default:
            std::cout << "\n\nPlease type the specific number.\n\n";
            language();
            break;
    }
}

当我编译它时,我没有收到任何错误或警告。但是当我第一次输入12或类似的单词时程序将结束。

在回答我之前,我还在学习 C++。(顺便说一句,我认为我真的不需要这么说?)因为这个我不知道如何解决这个问题。我的代码发生了什么?

4

4 回答 4

1

正如您char从输入中想要的那样,std::cin只会获取您在输入中键入的第一个字符并分配给choice. 它将忽略以下字符。

也就是说,您将在您的switch/case条件和的第一种情况下输入return

这取决于您期望用户提供什么输入。如果您只期望数字,我建议您使用int

#include <limits>    // needed for std::numeric_limits

void language() {
    int choice;
//  ^^^^

    // Ask user for something and input        
    std::cout << "Press 1 to exit the program\n\n";
    std::cin >> choice;

    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    // Getting user's input and run the code below and find for specific words
    switch(choice) {
    case 1:
        std::cout << "\n\nEnding program...";
        break;

    default:
        std::cout << "\n\nPlease type the specific number.\n\n";
        language();
        break;
    }
}

工作现场示例

于 2013-08-25T09:11:58.230 回答
0

Your code is exiting when you enter input starting with character 1.

于 2013-08-25T09:06:28.880 回答
0

You want the choice as string, not char since char only contains one character. Also you don't need break after the return statement

于 2013-08-25T09:07:27.920 回答
0

char choice;

will just receive a single character from standard input.

so all digits starting with 1 will end your program

instead use int choice; and change case to case 1:

    #include<limits>
    //...

    int choice;
    //...   
    std::cout << "Press 1 to exit the program\n\n";
    while(true)
    {
        if (std::cin >> choice)  
          break ;
        else {
            std::cout<<"Not an integer !"<<std::endl;
            std::cin.clear() ;
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
                     '\n') ;
        }
     }

    switch(choice) {
        case 1:
            //...
            break;
        default:
            std::cout << "\n\nPlease type the specific number.\n\n";
            language();
            break;
        }
于 2013-08-25T09:08:21.157 回答