c++ - 如果文件中的一行包含特定字符,则在 C++ 中查找

标签 c++ filestream

我已经从文本文件中读取了行,我想检查该行是否包含 $ 符号。

这就是我到目前为止所得到的:

int main() {

    ifstream data_store;
    string line;
    data_store.open("c:\\test.txt");


    while (!data_store.eof())
    {

        getline(data_store, line);
        if (line.find("$"))
        cout << "1: " << line << endl;
    }


    data_store.close();

    system("PAUSE");
    return 0;
}

此外,我如何将它们输出到文件?

最佳答案

检查一行是否包含使用 std::string::find 的内容需要检查 find 的返回值以确保它是有效的返回值。为此,我们将其与 std::string::npos 进行比较因为这就是 find() 在没有找到任何东西时将返回的内容。这就是它发现作为 std::string::npos 的每一行在被评估为 bool 时仍然被认为是 true 的原因。所以重构你的代码你会:

while (getline(data_store, line))
{
    if (line.find("$") != std::string::npos)
        cout << "1: " << line << endl;
}

我还更改了 while 循环,因为使用 eof 不是控制 while 循环的方法。有关更多信息,请参阅 Why is “while ( !feof (file) )” always wrong?

至于将字符串输出到文件,请参阅:How to write std::string to file?

关于c++ - 如果文件中的一行包含特定字符,则在 C++ 中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152992/

相关文章:

C++ Mixins——这是正确的实现方式吗?

c++ - Qt中如何显示从右到左书写的古字

c++ - C++中数组的元素计数

c# - 如何使用 System.IO.FileStream 读取希伯来文本?

c++ - 无法打开输入文件 ws2_32.libkernel32.lib

c++ - 如何在 C++ 中初始化双指针结构数组?

c# - FileStream.Read - 不使用循环读取流

Python:有 check_call 输出连续输出到文件吗?

java - 如何为操作系统上的所有其他进程锁定 Java 应用程序中的文件?

c# - 将文件从外部源传递到 .ashx 处理程序?