gpt4 book ai didi

c++ - 在 vector 中添加字符串数字时出错

转载 作者:行者123 更新时间:2023-11-28 03:17:56 25 4
gpt4 key购买 nike

我正在从文件中读取单词,输出应该是单词和出现该单词的行号。我的代码运行良好,但我在存储行号的 vector 中遇到了问题每一个字。

例如文本文件:

I am for truth
no matter who tells it,
I am for justice,
no matter who it is for or against
Malcom X

我得到的输出:

I 13
am 1133
for 111333444444
truth 1111
no 24
matter 2244
who 222444
tells 2222
it 222224444
justice 3333
is 44444
or 4444444
against 44444444
Malcom 5
X 55

我期待的输出:

against 4 
matter 2, 4
am 1, 3
no 2, 4
for 1, 3, 4
or 4
I 1, 3
tells 2
is 4
truth 1
it 2, 4
who 2,4
justice 3
X 5
Malcolm 5

这是我的代码:

int main(int argc, char *argv[]) {

fstream infile ;
BSTFCI <string>* bst = new BSTFCI<string>();
string word;
string line;
vector <string>words;
vector <string>line_no;
int count = 0;
infile.open("test.txt" , ios::in);
if(infile.fail())
{
cout<<"Error Opening file"<<endl;
return 0;
}

while(getline(infile , line))
{
++count;
istringstream buffer(line);
ostringstream counter;
while (buffer >> word)
{

for(int i=0 ; i<word.size();i++) {
if(ispunct(word[i]))
word.erase(i,1);
}

if(!bst->search(word)) {
bst->insert(word);
words.push_back(word);
counter << count;
line_no.push_back(counter.str());
} else {
counter<<count;
for(int k=0;k<words.size();k++) {
if(word==words.at(k))
line_no.at(k)+=counter.str();
}
}

}
}

for(int i=0;i<words.size();i++)
cout << words.at(i) << " " << line_no.at(i) << endl;

infile.close();
return 0;

}

最佳答案

尝试删除 counter<<count .在我看来,这是错误的原因。如果它不起作用删除count++;

关于c++ - 在 vector 中添加字符串数字时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16265756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com