我对编程很新,很抱歉,如果我说的话没有意义!
我目前正在尝试制作一个程序,并发现自己陷入了一个小问题。我制作了一个名为choice
,choice[0] = one
,choice[1] = two
的阵列
当我向用户询问某些事情时。
我希望能够让用户从阵列中挑选出他们想要的东西
cout << "Which would you like? Enter '0' for one, enter '1' for two " << endl;
cin >> choice
我理解cin >> choice
部分是错误的,但我不知道该放什么,任何建议都会很棒,谢谢!
好的一些示例代码:
#include <iostream>
#inclue <string>
using namespace std;
int main()
{
string choice[2], userchoice;
choice[0] = "Red";
choice[1] = "Blue";
cout << "Type '0' to choose red, type '1' to choose blue" << endl;
cin >> userchoice;
cout << "You chose " << choice[userchoice] << endl;
}
我希望它能打印出“你选择红色”或“你选择蓝色”,只需输入“0”或“1”
答案 0 :(得分:2)
您希望输入成为数组的索引,如下所示:
size_t index;
cout << "Which would you like? Enter '0' for one, enter '1' for two " << endl;
cin >> index;
cout << "\nYou chose: " << choice[index] << endl;
答案 1 :(得分:0)
#include <iostream>
#include <string.h>
#include <cstdlib>
using namespace std;
string arr[5] = { "one" , "two" , "three" , "four" , "five" };
string returnArrayPos( int pos )
{
if( pos >= 0 && pos < ( sizeof( arr ) / sizeof( *arr ) ) )
return arr[pos];
else
return "Wrong Index!";
}
int main() {
int pos = 0;
cin >> pos;
cout << returnArrayPos( pos ) << endl;
return 0;
}
为您的问题提供更高级的解决方案。并保存输入错误的索引。
答案 2 :(得分:0)
#include <iostream>
#inclue <string>
using namespace std;
int main()
{
string choice[2];
int userschoice;
choice[0] = "Red";
choice[1] = "Blue";
cout << "Type '0' to choose red, type '1' to choose blue" << endl;
cin >> userschoice;
if(userschoice == 0)
{
cout << "You chose " << choice[0] << endl;
}
else if(userschoice == 1)
{
cout << "You chose " << choice[1] << endl;
}
}
答案 3 :(得分:0)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string choice[2];
int userchoice;
choice[0] = "Red";
choice[1] = "Blue";
cout << "Type '0' to choose red, type '1' to choose blue" << endl;
cin >> userchoice;
if(userchoice>1) cout<<"Sorry my vocabulary isn't large enough..";
else
cout << "You chose " << choice[userchoice] << endl;
return 0;}