代码在Linux上运行良好,但在Windows操作系统上提供了不同的输出

时间:2012-05-21 06:09:10

标签: c++ windows linux console mingw

我一直想知道为什么下面的代码在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]:

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-3)

我在MSVC 2010中编译了这段代码,它运行正常。你使用什么编译器?