运行代码

时间:2018-03-05 21:53:36

标签: c++

我正在尝试学习C ++,但我无法解决问题。

我的代码:

#include <iostream>
using namespace std; 

int userContinue = true;
int userContinueString;
int getUserInput() {
    int userInput1;
    int userInput2;
    cout << "Please enter your first number: ";
    cin >> userInput1;
    cout << endl << "Please enter your second number: ";
    cin >> userInput2;
    cout << endl << "The result of the two numbers together: " << userInput1+userInput2;
    userInput1 = 0;
    userInput2 = 0;
    return 0;
}

int main()
{
    while (userContinue == true) {
        getUserInput();
        cout << endl << "Would you like to continue? (Y/N): ";
        cin >> userContinueString;
        if (userContinueString ='Y') {

        }
        else {
        userContinue = false;
        }
    }
   return 0;
}

代码工作正常,直到我输入“Y”蚂蚁然后它保持循环,如下所示:Video

1 个答案:

答案 0 :(得分:2)

首先,确保使用-Wall -Wpedantic等警告开关编译代码。这些开关将帮助您。例如,在原始代码中,我的编译器会输出以下警告:

prog.cpp:25:28: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
    if (userContinueString = 'Y') {
        ~~~~~~~~~~~~~~~~~~~^~~~~
prog.cpp:25:28: note: place parentheses around the assignment to silence this warning
    if (userContinueString = 'Y') {
                           ^
        (                       )
prog.cpp:25:28: note: use '==' to turn this assignment into an equality comparison
    if (userContinueString = 'Y') {
                           ^
                           ==
1 warning generated.

然后,我使用==修复了相应的行,这已在评论中提出。然后,您的比较应该不区分大小写。最后,您想比较char'y'的{​​{1}}个对象:

'Y'

编辑。我已经通过考虑David的评论来改进答案。请注意使用#include <cctype> #include <iostream> using namespace std; int userContinue = true; char /* not int */ userContinueString; int getUserInput() { int userInput1; int userInput2; cout << "Please enter your first number: "; cin >> userInput1; cout << endl << "Please enter your second number: "; cin >> userInput2; cout << endl << "The result of the two numbers together: " << userInput1 + userInput2; userInput1 = 0; userInput2 = 0; return 0; } int main() { while (userContinue == true) { getUserInput(); cout << endl << "Would you like to continue? (Y/N): "; cin >> userContinueString; if (std::tolower(userContinueString) == 'y') { } else { userContinue = false; } } return 0; } #include <cctype>

编辑。我尝试通过尝试解决以下“学习C ++”评论来进一步改进答案:

std::tolower