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