-2
我正在创建一个程序,该程序只读取文本的输入文件,并在该输入文件中创建单词的矢量。我现在的程序只提示用户输入文件名,然后停止运行。我的文本文件只有3个字用于测试,但在程序结束时,我希望能够读取诸如故事等大型文本文件。
我的代码:将单词的输入文件转换为矢量 - C++
#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;
}
你试过跟踪它吗?你真正的问题是什么? – JTeagle 2012-03-12 17:52:58
你的循环**方式**复杂。相反,说'std :: vector words((std :: istream_iterator(fin)),std :: istream_iterator());'并且完成它。 –
2012-03-12 17:57:04
你的代码没有意义。你正在读一个单词,然后把它扔掉,然后读一个单词,扔掉它,然后读另一个单词并以一种过度复杂的方式将它添加到一个矢量中。请考虑从[入门书]开始(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – Philipp 2012-03-12 20:06:48