它可能是一个简单的答案,我希望它很容易理解我的问题。我有一个包含很多行和几个段落的文本文档
有没有一种方法可以将所有行合并为一行而无需手动操作?我之所以问这个问题是因为假设我正在搜索只有一个段落的文档中的特定单词。(假设该段落有 10 行)如果该单词在该段落中,则假设返回段落 1 被接受。但是我的程序在做什么奇怪的事情,而不是给我这样的输出:
paragraph1:accepted
paragraph2:accepted
paragraph3:accepted
paragraph4:accepted
paragraph5:accepted
paragraph6:accepted
paragraph7:accepted
paragraph8:accepted
paragraph9:accepted
paragraph10:accepted
这是读取我的文档的代码
void processParagraph(std::string ¶graph, size_t paragraphNumber)
{
ifstream input;
input.open("data.txt"); //opens the text file with the documents
if (input.fail()) //if the file doesn't open
{
cout << "file not found" << endl;
return;
}
if (isMyWordThere(paragraph)) //if the word im looking its there
cout << "paragraph " << paragraphNumber << ": accepted" << endl;
else // if the word its not there
cout << "paragraph " << paragraphNumber << ": not accepted" << endl;
paragraph.clear(); // reset the paragraph to handle the next one.
std::string line;
std::string paragraph;
size_t paragraphNumber = 0;
while ( getline(input, line) ) // read a LINE
{
if ( !line.empty() ) // paragraph not finished
{
paragraph.append("\n").append(line);
}
else // paragraph finished, because we found an empty line
{
++paragraphNumber;
processParagraph(paragraph, paragraphNumber);
}
}
if ( !paragraph.empty() )
{
processParagraph(paragraph, paragraphNumber);
}
}
它有一种方法可以将所有行合并为一个,或者我可以更改我的代码以便它不计算行数?
输入文件如下所示:(我正在寻找单词“hello”)
hello world
hello everyone
hello All
输出应如下所示
paragraph 1: accepted
但我得到的是
paragraph 1: accepted
paragraph 2: accepted
paragraph 3: accepted