【问题标题】:How do I use an if statment to check if a string literal is a certain word or phrase如何使用 if 语句检查字符串文字是否是某个单词或短语
【发布时间】:2015-05-29 22:27:25
【问题描述】:

我还是编码新手,正在尝试找出简单的对话,编译时出现以下错误:

错误:无法从 'std:: 转换 'str.std::basic_string<_chart _traits _alloc>::operator=, std::allocator >(((const char*)"good"))' basic_string' 到 'bool' if (str = "good") {

错误:无法从 'std:: 转换 'str.std::basic_string<_chart _traits _alloc>::operator=, std::allocator >(((const char*)"bad"))' basic_string' 到 'bool' 否则 if (str = "bad") {

我从以下代码中得到这些错误。请记住,我对此还是很陌生:

// random practice on conversation
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string str;
    string bad;

    cout << "How has your day been?  \n";
    cin >> str;
    if (str = "good") {
        cout << "Thats good to hear!\n";
    }
    else if (str = "bad") {
        cout << "That's too bad, what happened?  \n";
        cin >> bad;
        cout << "I'm sorry to hear that...\n";
    }
    else {
        cout << "I'm sorry, I couldn't understand you...\n";
    }
}

【问题讨论】:

  • c++ 中的平等使用==,而不是=
  • 然后解决了,这让我感觉更初学者,谢谢你的帮助。我不能也可以相信这是唯一的问题......哦,还有很多东西要学
  • 你的编译器真的没有给你warning about = vs. ==吗?
  • 我发布的是我得到的唯一两个错误,我使用的是编译器 DEV-C++ 5.10

标签: c++ string if-statement


【解决方案1】:

= 不是比较运算符,它是赋值运算符。 == 是比较运算符。

if( str == "bad" )
{
...
}

【讨论】:

    【解决方案2】:
    if(str == "good"){
    
    
    }
    

    您需要双等号,否则您将字符串变量str 设置为"good""bad",而不是检查它是否等于。

    【讨论】:

      【解决方案3】:

      在 C/C++ 中,== 运算符不适用于字符串。如果要比较两个字符串 s1 和 s2,请使用 s1.compare(s2) 或该函数的其他变体。为此,您还可以使用 strncmp() 函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        • 2020-01-15
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多