错误:在'if'和'else'C ++之前的预期unqualified-id

时间:2016-01-07 03:30:32

标签: c++

我无法弄清楚代码中的不合格ID是什么,或者如何解决它。

#include <iostream>
#include <string>

using namespace std;

int main ()
{  
    string x;
    getline(cin, x);
}

if (x == 1) {
    cout << "x is 1";
}

else if (x == 2) {
    cout << "x is 2";
}

else {
    cout << "value of x unknown";
}

上面的旧代码。下面的新代码

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()

 {
     string mystr;
     int number;
    cout << "pick a number ";
    getline (cin, mystr);
    stringstream(mystr) >> number;

if (number == 1) 
  cout << "x is 1";

else if (number == 2) 
  cout << "x is 2";

else 
  cout << "its not one or 2";
}

这需要进行任何改进吗?感谢所有帮助并帮助我。

1 个答案:

答案 0 :(得分:0)

问题在于:

int main ()
{  
    string x;
    getline(cin, x);
} // <-- ERRONEOUS!

if (x == 1) {
...

您过早地终止main(),导致其余代码超出任何函数,从而导致编译错误。您需要将错误的}移到main()的末尾。

进行更改后,您会收到operator==()错误,因为您无法使用string运算符将int==进行比较。您需要将int值更改为字符串,然后将其进行比较。

试试这个:

#include <iostream>
#include <string>

using namespace std;

int main ()
{  
    string x;
    getline(cin, x);

    if (x == "1") {
        cout << "x is 1";
    }

    else if (x == "2") {
        cout << "x is 2";
    }

    else {
        cout << "value of x unknown";
    }

    return 0; // <-- don't forget this

} // <-- brace moved here

如果您确实想要比较数值,则需要先将x的值转换为int变量(并且不要忘记错误检查):

#include <iostream>
#include <string>
#include <sstring>

using namespace std;

int main ()
{  
    string x;

    if (!getline(cin, x)) {
        cout << "unable to read x";
    }
    else {
        istringstream iss(x);
        int value;

        if (!(iss >> value)) {
            cout << "x is not a number";
        }

        else if (value == 1) {
            cout << "x is 1";
        }

        else if (value == "2") {
            cout << "x is 2";
        }

        else {
            cout << "value of x unknown";
        }
    }

    return 0;
}