1

我一直想知道为什么下面的代码在 Windows 操作系统上给了我不同的输出。同时,相同的代码在 Ubuntu 上运行良好。

#include <iostream>
#include <cstring>

using namespace std;

string getname(void);
char getgender(string);
void setinfo(string,char);

int main()
{
    string customer = "";
    char gender;
    do {
        do{
            customer = getname();
        }while(customer =="");
        do{
            gender = getgender(customer);
            cout << "Gender in Main block is: " << gender << endl;
        }while(gender != 'm' && gender != 'f');
        setinfo(customer,gender);
        break;
    }while(1);
    return 0;
}

string getname(void)
{
    string name = "";
    cout <<"Please Enter your Name: " ;
    getline(cin,name);
    if(name == ""){
        cout << "Error: Name cannot be empty" <<  endl;
    }
    return name;
}

char getgender(string name)
{
    char gender;
    string strgender;
    cout << "Male / Female[m/f]: ";
    getline( cin,strgender);
    gender = strgender[0];
    strgender.clear();
    gender = tolower(gender);
    if(gender == 'm' || gender == 'f'){
        cout << "Gender in getgender() is: " << gender << endl;
        return gender;
    }
    else
        cout <<"Error: Must be m/ f" << endl;
}

void setinfo(string customer, char gender)
{
    string prefix;
    if(gender == 'm')
        prefix =  "Mr.";
    else
        prefix = "Ms/Mrs.";
    cout << "Hello " << prefix << " " << customer << endl;
    cout << "Welcome to TOWER HEIGHT" << endl;
}

在我的 Ubuntu 机器上,这段代码运行良好。但是当我在 Windows 上编译和运行它时,我得到了不同的输出,并且它一直在 getgender() 处循环。

    Please Enter your Name: My Name
    Male / Female[m/f]: m
    Gender in getgender() is: m
    Gender in Main block is: ╕

    Male / Female[m/f]: f
    Gender in getgender() is: f
    Gender in Main block is: ╕

    Male / Female[m/f]:
4

2 回答 2

5

当设置为无效值时,您的getgender()函数会在没有返回值的情况下结束。gender这可能会导致编译器为该函数生成错误代码;尝试通过在末尾添加“return 0”来修复它。

您应该顺便打开 Linux 系统上的警告(通过使用-Wall编译器标志)。这会使问题立即显而易见:

example.cpp: In function ‘char getgender(std::string)’:
example.cpp:54: warning: control reaches end of non-void function
于 2012-05-21T06:24:13.423 回答
-2

我在 MSVC 2010 中编译了这段代码,它工作正常。你用的是什么编译器?

于 2012-05-21T06:15:22.133 回答