简体   繁体   English

如何使用 getline 从 txt 文件中打印正确的行

[英]How to use getline to print the correct line from txt file

I'm trying to create a program that will search a given directory txt file for a certain string.我正在尝试创建一个程序,该程序将在给定的目录 txt 文件中搜索某个字符串。 Once that string is found, the program will print onto the screen the information only on that line within the txt file.找到该字符串后,程序将仅将 txt 文件中该行的信息打印到屏幕上。 My code is able to check and see if the string is inside the file, but instead of printing only the line it's contained in, it prints everything but the line I want.我的代码能够检查并查看字符串是否在文件中,但它不是只打印它包含的行,而是打印除我想要的行之外的所有内容。

while(!inF.eof()){
    getline(inF, hold);
    if(hold.find(crnS)){
        isFound = 1;
        cout << hold << endl; 
    }                          
}

There are two problems with your code:您的代码有两个问题:

Use this instead:改用这个:

while (getline(inF, hold)) {
    if (hold.find(crnS) != string::npos) {
        isFound = 1;
        cout << hold << endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM