C ++ if / else语句问题

时间:2016-06-30 19:18:01

标签: c++ xcode c++11 if-statement

前几天我正在使用xcode,正在开发基于文本的对话游戏。

#include <iostream>

int main()
{
    std::cout<<"Conversation simulator requires you to type in all caps for all  of your replies"<<std::endl;
    std::cout<<"Type your first and last name!"<<std::endl;
    std::string fname = " ";
    std::string lname = " ";
    bool samename = false;
    std::cin>> fname >> lname ;
    if  (fname == "MUSCLE" and lname == "MAN")
        std::cout<< "Wow, we have the same first and last name!"<<std::endl;
        samename = true;
    else
        std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;

return 0;
}

对我来说似乎没有什么不对,但Xcode不会因为在这条线上而无法运行:

else

它期待一个表达?我无法想到这可能意味着什么。

5 个答案:

答案 0 :(得分:9)

如果您希望在if下执行多个语句,则需要大括号。这是一个为我编译的修复程序。

#include <iostream>

int main()
{
        std::cout<<"Conversation simulator requires you to type in all caps for all  of your replies"<<std::endl;
        std::cout<<"Type your first and last name!"<<std::endl;
        std::string fname = " ";
        std::string lname = " ";
        bool samename = false;
        std::cin>> fname >> lname;
        if  (fname == "MUSCLE" and lname == "MAN") {
                std::cout<< "Wow, we have the same first and last name!"<<std::endl;
                samename = true;
        } else {
                std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;
        }
        return 0;
}

答案 1 :(得分:5)

你忘记了if-block的花括号:

if  (fname == "MUSCLE" and lname == "MAN") {
    std::cout<< "Wow, we have the same first and last name!"<<std::endl;
    samename = true;
}
else
    std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;

没有它们,只有下一个语句(在你的情况下输出)属于if。因此,在下一行中设置标记会导致else不正确。

答案 2 :(得分:3)

您忘记了以下if .. else语句中的括号是修复。

#include <iostream>

int main()
{
    std::cout<<"Conversation simulator requires you to type in all caps for all  of your replies"<<std::endl;
    std::cout<<"Type your first and last name!"<<std::endl;
    std::string fname = " ";
    std::string lname = " ";
    bool samename = false;
    std::cin>> fname >> lname ;
    if  (fname == "MUSCLE" and lname == "MAN"){
        std::cout<< "Wow, we have the same first and last name!"<<std::endl;
        samename = true;
    } else {
        std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;
    }
return 0;
}

答案 3 :(得分:1)

你错过了括号:

If () {
} else {
}

答案 4 :(得分:0)

我相信必须使用Open-Close花括号:

if  (fname == "MUSCLE" and lname == "MAN")
{
    std::cout<< "Wow, we have the same first and last name!"<<std::endl;
    samename = true;
}
else
    std::cout<< fname << " "<< lname << "is a very nice name"<<std::endl;