“to_string”在字符串数组中如何工作?

0 c++ string if-statement substring

我想组合txt文件中每行的前4个字符并将其与我拥有的关键字进行比较,但是当我组合这些字符时,我得到这4个字符的ascii数字的总和(无论如何)。我怎么解决这个问题。我的代码在这里:当我调试时,我看到字符串搜索(变量)是321。

int main() {
    ifstream file("sentence.txt");
    
    if (file.is_open()) {
        string line;
        while (getline(file, line)) {
            string search = to_string(line[0] + line[1] + line[2]); // you see what I mean
            if ("dog" == search) {
                cout << "there is dog";
            }
            else {
                cout << "there is no dog"<<endl;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

该函数std::to_string()旨在将数字转换为字符串表示形式。这不是你所需要的。

无需创建新字符串search来检查字符串是否line以 string 开头"dog"

创建新字符串的search效率很低。

相反,你可以写例如

if ( line.compare( 0, 3, "dog" ) == 0 ) {
    cout << "there is dog";
}
else {
    cout << "there is no dog" << endl;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您的编译器支持 C++20,您也可以编写:

if ( line.starts_with( "dog" ) ) {
    cout << "there is dog";
}
else {
    cout << "there is no dog" << endl;
}
Run Code Online (Sandbox Code Playgroud)