【问题标题】:Trying to print out a matching char variable to cout尝试将匹配的 char 变量打印到 cout
【发布时间】: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


【解决方案1】:

它不工作的原因是因为== char 数组的运算符没有重载。您想使用 strcmp 而不是 == 运算符(实际上您应该使用字符串,因为无论如何这是 c++ ......)。

#include <cstring>

...

if(strcmp(sum, "CocaCola") == 0 || strcmp(sum, "cocacola") == 0)
{
    cout << "you've chosen CocaCola " ;
}

如果您想使用严格的 c++ 来执行此操作。然后删除 char 数组 sum 并改为这样做

getline(cin, choice);

if( choice == "CocaCola" || choice == "cocacola" )
{
    cout << "you've chosen CocaCola " ;
}

【讨论】:

  • 我试图只使用字符串,但是当我使用 == 运算符时,我在 cmd 上遇到了不断的错误。我宁愿只坚持使用 c++,我这样做只是为了了解我没有严格的方法来做到这一点。
  • 哇,我可能只是有语法错误或什么?不知道我怎么会错过你答案的第二部分,无论如何感谢 c++ 部分和 c 洞察力。
【解决方案2】:

尝试使用以下代码修改您的代码:

strncpy(sum, choice.c_str(), sizeof(sum));
sum[sizeof(sum) - 1] = 0;

string sum_string(sum);

if( (sum_string== "CocaCola") || (sum_string== "cocacola") )
{
     cout << "you've chosen CocaCola " ;
 }

【讨论】:

  • 谢谢,它工作得很好,但我现在只会坚持使用 c++。我只使用 c bc 我在论坛上找到它,无论如何感谢 C 洞察力。 :)
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多