我已经从文本文件中读取了行,我想检查该行是否包含 $ 符号。
这就是我到目前为止所得到的:
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/