【发布时间】:2015-10-13 11:00:07
【问题描述】:
我绝对是编程的初学者。不,这也不是家庭作业。我正在尝试自己学习它。如标题本身所述,我想输入一个 .txt 文件并从文件中找出一个特定的单词。但这不完全是我想要的。我宁愿想要单词所在的行号,以便我可以使用此行号并在此特定行之后打印出 .txt 文件中的所有行。我在 youtube 上找到了这段代码,它向我展示了如何找到这个词。我对其进行了一些修改,现在它给了我搜索单词状态的行(不是行号)。我附上代码。
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
string find_word(string file, string word)
{
int offset;
string line1;
ifstream Myfile;
Myfile.open(open);
if (Myfile.is_open())
{
while (!Myfile.eof())
{
getline(Myfile, line1);
if ((offset = line1.find(word,o)) != string::npos)
{
return line1;
}
}
Myfile.close();
}
else
cout << "couldn't open...." << endl;
}
int main ()
{
string c = find_word("test.txt", "$COOR");
cout << c;
cin.get();
return 0;
}
现在文本文件只包含 8 行,“$COOR”位于第 4 行。程序只给了我整行。但我想要行号,以便我可以打印出第 4 行之后的行。
稍后我想测试它是否具有多行的文件,即超过 50000000 左右。
【问题讨论】:
-
如果你的代码真的看起来像这样,你应该花一些时间正确缩进它,这样更容易阅读。如果看起来不是这样,请编辑问题以正确缩进(您可以选择一个代码块并按 Ctrl-K 或
{}按钮缩进一个块)。 -
另见kayari.org/cxx/antipatterns.html#istream-check和kayari.org/cxx/antipatterns.html#istream-eof——你应该检查
getline的结果而不是测试eof -
请缩进您的代码。使用
while ( !file.eof() )是个坏主意,请在此处查看原因:stackoverflow.com/questions/5605125/…