首页 > 解决方案 > c++中if条件下字符串比较的问题

问题描述

我正在尝试输入一个带空格的字符串,直到文件结束。然后我将它与 if 条件中的另一个字符串进行比较,条件说,如果字符串匹配,它将打印 True,否则为 False。但是我的代码有问题。根据我的输入,所有输出都应该是“真”。但它仅在最后一行打印为 true。这里出了什么问题?

代码 :

#include<bits/stdc++.h>
using namespace std;

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    
    string s;

    while(getline(cin, s)){
        if(s == "my name is corey")
            cout<<"True"<<endl;
        else
            cout<<"false"<<endl;
    }
}

输入 :

my name is corey
my name is corey
my name is corey
my name is corey

输出:

false
false
false
True

标签: c++stringgetline

解决方案


推荐阅读