【发布时间】:2012-03-12 17:51:01
【问题描述】:
我正在创建一个程序,它仅读取文本输入文件并在该输入文件中创建单词向量。我现在的程序只提示用户输入文件名,然后停止运行。我的文本文件中只有 3 个单词用于测试,但在程序结束时我希望能够阅读大型文本文件,例如故事。
我的代码:
#include<string>
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
int main(){
string filename; //name of text file
string wordsFromFile; //the words gathered from the text file
cout << "Please enter the name of your text file" << endl;
cin >> filename;
ifstream fin(filename.c_str());
fin >> wordsFromFile;
while(fin >> wordsFromFile)
{
fin >> wordsFromFile;
vector<string>word;
for(int i=0; i<=word.size(); i++) {
word.push_back(wordsFromFile);
cout << word[i];}
}
fin.close();
return 0;
}
【问题讨论】:
-
你试过追踪它吗?您的实际问题是什么?
-
你的循环方式太复杂了。相反,请说
std::vector<std::string> words((std::istream_iterator(fin)), std::istream_iterator());并完成它。 -
您的代码没有意义。您正在阅读一个单词,然后将其扔掉,然后再阅读另一个单词,将其扔掉,然后再阅读另一个单词并以过于复杂的方式将其添加到向量中。请考虑以introductory book 开头。
-
我确实有一本入门书。不过,本书并未涵盖我在该程序中尝试做的事情的范围。
标签: c++ string input vector fstream