gpt4 book ai didi

c++ - 将一段文本读入字符串 vector

转载 作者:搜寻专家 更新时间:2023-10-31 01:49:40 26 4
gpt4 key购买 nike

我正在尝试将一段文本读入一个字符串 vector ,然后创建一个字典来记录每个单词出现的次数。到目前为止,它只加载文本的第一个单词,我不确定如何进行。我知道我有点不清楚如何正确使用这些成员函数。

int main()
{
ifstream input1;
input1.open("Base_text.txt");

vector<string> base_file;
vector<int> base_count;


if (input1.fail())
{
cout<<"Input file 1 opening failed."<<endl;
exit(1);
}

make_dictionary(input1, base_file, base_count);


}

void make_dictionary(istream& file, vector<string>& words, vector<int>& count)
{


string line;


while (file>>line)
{
words.push_back(line);
}

cout<<words[0];



}

预期输出:

This is some simple base text to use for comparison with other files.
You may use your own if you so choose; your program shouldn't actually care.
For getting interesting results, longer passages of text may be useful.
In theory, a full novel might work, although it will likely be somewhat slow.

实际输出:

This 

最佳答案

我想你得搬家了cout << words[0]在循环内,否则它只会在循环结束时被调用一次。不过,每次迭代只会打印第一个单词。所以,每次打印最后一个词:

while (file>>line)
{
words.push_back(line);
cout<<words.back(); // or cout << line, same thing really
}

最后一件事 - while(file >> line)将逐字阅读,而不是像变量名称所暗示的那样逐行阅读。如果需要,请使用 while (getline(file, line)) .

关于c++ - 将一段文本读入字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243977/

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