这是我高中编程课的作业,我似乎没有做错任何事。但是,当我在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;
}
答案 0 :(得分:7)
您正在混合字符和字符串。可悲的是,C ++允许一个&#34;字符&#34;比如'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
将输入映射到输出字符串。对于上面的示例而言,这可能就足够了,它会使代码更具可读性。
答案 1 :(得分:0)
如果你绝对必须使用switch case进行此分配,那么在你的switch语句之前你必须转换&#39;将您的字符串转换为整数值。这方面的一个例子是......
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 / else方法。