这是我高中编程课的作业,我似乎没有做错什么。然而,当我在VS express 2013中运行Windows调试器时,所有的情况都是默认的,即使我在所有的情况下都有break;。我不知道我做错了什么,也根本查不出来。
// mauroc_switch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
char yesform;
cout << "Type ''yes,'' lowercased and romanized, in a non-English language." << endl;
cin >> yesform;
//***Here is the switch statement.***
switch (yesform){
case 'yes':
cout << "This is the English ''yes.'' Please type a non-English version of ''yes.'' " << endl;
break;
case 'ja':
cout << "This is the German form of ''yes.'' It is also the Swedish and Norwegian form of ''yes.'' " << endl;
break;
case 'si':
cout << "This is both the Spanish and the Italian form of ''yes.'' " << endl;
break;
case 'oui':
cout << "This is the French form of ''yes.'' " << endl;
break;
case 'hai':
cout << "This is the Japanese form of ''yes.'' " << endl;
break;
case 'da':
cout << "This is the Russian form of ''yes.'' " << endl;
break;
case 'ne':
case 'ye':
cout << "This is a Korean form of ''yes.'' " << endl;
break;
case 'naam':
case 'aiwa':
cout << "This is an Arabic form of ''yes.'' " << endl;
break;
case 'sim':
cout << "This is the Portuguese form of ''yes.'' " << endl;
break;
case 'haan':
cout << "This is the Hindi form of ''yes.'' " << endl;
break;
default:
cout << "You either made a typo or you typed ''yes'' in an unsupported language. Please try again. ";
break;
}
system("pause");
return 0;
}发布于 2015-05-01 05:51:00
您正在混合字符和字符串。遗憾的是,C++允许使用像'yes'这样的“字符”,但这并不是您所想的那样。另一个问题是,一旦切换到字符串(std::string),就不能再使用switch,但是需要一系列if-else语句或其他方法来匹配字符串。
这里有一个简单的例子,应该是可行的:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string yesform;
cout << "Type ''yes,'' lowercased and romanized, in a non-English language." << endl;
cin >> yesform;
if( yesform == "yes" )
cout << "This is the English ''yes.'' Please type a non-English version of ''yes.'' " << endl;
else if( yesform == "ja" )
cout << "This is the German form of ''yes.'' It is also the Swedish and Norwegian form of ''yes.'' " << endl;
else
cout << "You either made a typo or you typed ''yes'' in an unsupported language. Please try again. ";
return 0;
}在您的示例中,一旦将输入读入字符串,请尝试使用std::map将输入映射到输出字符串。对于上面的示例来说,这可能就足够了,它将使代码更具可读性。
发布于 2015-05-01 06:12:29
如果你必须在这个赋值中使用switch case,那么在你的switch语句之前,你必须将字符串‘转换’成一个整数值。一个这样的例子是...
enum yesLanguage {YES, JA, OUI, ..., CI};
yesLanguage yesAnswer = YES;
if (yesform == 'yes'){
yesAnswer = YES;
}
else if(yesform == 'ja'){
yesAnswer = JA;
}以此类推,然后在您的交换机情况下,您将拥有
switch(yesLanguage)
case YES:
Your YES output here;
break;
case JA:
.........以此类推,剩下的代码就像你的原始帖子中的上面那样。
但是,如果您不需要来使用切换大小写,那么就像我上面的帖子中所说的那样,使用if /方法。
编辑以添加枚举。 http://en.cppreference.com/w/cpp/language/enum
https://stackoverflow.com/questions/29978393
复制相似问题