【发布时间】:2014-01-07 14:57:53
【问题描述】:
所以我正在尝试制作一个可口可乐机器来打印出用户选择喝的东西。 基本上,我不想让用户输入像“cocacola”这样的单词作为字符串,然后我将其转换为 char 类型并与 if 语句一起使用。
但是当我运行我的代码时它不起作用。
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;
int main(){
cout << "You approach the Cola Machine..." ;
cout <<"these are the different drinks it offers." << endl << endl ;
cout <<"CocaCola\nSquirt\nSprite\nWater\nHorchata" << endl << endl ;
cout <<"Type in what you would like to drink: " ;
string choice ;
char sum[300] ;
cin >> choice ;
strncpy(sum, choice.c_str(), sizeof(sum));
sum[sizeof(sum) - 1] = 0;
if(choice == choice) {
if((sum == "CocaCola" || sum == "cocacola")){cout << "you've chosen CocaCola " ;}
}
return 0 ;
}
编辑:我不小心用 switch 语句代替了 (if)。
【问题讨论】:
-
涉及到 C 字符串有什么特别的原因吗?
-
不要使用 strcpy。它已被弃用,它是 C
-
我一直在寻找一种方法来完成这项工作,首先我尝试了 static_cast 但没有运气,我找到了一个使用 strcpy 作为解决方案的在线论坛。
标签: c++ string if-statement strcpy