如何计数在文本文件中的哪一行的单词是c++



我有一个练习,我需要在一个以用户输入符号开头的文本文件中查找单词。我还需要确定该单词在哪一行,并在文本不同的文本文件中输出。我设法编写代码来输出以symbol开头的单词,并计算单词在文本中的位置,但我不知道如何计算该单词在哪一行。我还需要找到那些有?!等符号的单词,而不仅仅是' '例如,如果我想查找以c开头的单词,那么我的程序只会找到"cerebral, cortex, could, create"但不是"构造,有能力,计算机";从我的示例输入下面的代码。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream input;
fstream output;
string word, line;
char startOfWord;
cout << "I wanna find words starting with symbol: n";
cin >> startOfWord;
int lineNumber = 0;
input.open("f.txt");
output.open("f1.txt");
while (!input.eof()) {
input >> word;
lineNumber++;
if (word.length() > 40) {
continue;
}
if (word[0] == startOfWord) {
output << word << ' ' << lineNumber << 'n';
}
}
input.close();
output.close();
return 0;
}

示例输入:用户想查找以a开头的单词。

f.txt:

A Stanford University project to?construct a model 
of the cerebral cortex in silicon could help scientists 
gain a better understanding of the brain, in order to 
create more,capable.computers and advanced 
neural prosthetics. 

输出:f1.txt

a 1
a 3
and 4
advanced 4

您正在逐字读取文件,计算每个单词。你需要逐行读取文件,每行计数,然后你可以从每行读取单词。

试试这个:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream input;
ofstream output;
string word, line;
char startOfWord;
cout << "I wanna find words starting with symbol: n";
cin >> startOfWord;
int lineNumber = 0;
input.open("f.txt");
output.open("f1.txt");
while (getline(input, line)) {
++lineNumber;
istringstream iss(line);
while (iss >> word) {
if (word.length() > 40) {
continue;
}
if (word[0] == startOfWord) {
output << word << ' ' << lineNumber << 'n';
}
}
}
input.close();
output.close();
return 0;
}

我做到了!这个工作!

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
void getWordsFromLine(string word, int index, vector<string> &memory) { //funkcija kas izvelk vardus no rindam
string newWord;
for (int i = index; i < word.length(); i++) {
if (word[i] == ')' || word[i] == '(' || word[i] == '.' || word[i] == ',' || word[i] == '=' || word[i] == '?' || word[i] == '!') { //parbauda visas iespejamas pieturzimes
i++;
getWordsFromLine(word, i, memory);
break;
}
else {
newWord += word[i];
}
}
memory.push_back(newWord);
}
int main() {
int ok;
do
{
ifstream input;
ofstream output;
string word, line;
char startOfWord;
char symbol;
cout << "I wanna find words starting with symbol: n";
cin >> startOfWord;
int lineNumber = 0;
input.open("f.txt");
output.open("f1.txt");
while (getline(input, line)) {
++lineNumber;   //skaita rindas
istringstream iss(line);
while (iss >> word) {
if (word.length() > 40) {
continue;
}
vector<string> words;
getWordsFromLine(word, 0, words);
for (int i = 0; i < words.size(); i++) {
if (words[i][0] == startOfWord) { //atrod vardus ar sakuma simbolu
output << words[i] << ' ' << lineNumber << 'n';
}
}
}
}
input.close();
output.close();
cout<<"Vai turpinat (1) vai beigt (0)?"<<endl;
cin>>ok;
} while (ok==1);
return 0;
}

最新更新