【发布时间】:2014-11-27 08:04:35
【问题描述】:
我正在创建一个程序,它将用户输入的单词写入已经有其他单词开头的文本文件。像这样:
"words.txt"
apples
oranges
bananas
我想做的是将其他单词添加到列表中,然后在屏幕上输出所有单词。我写了一个程序,但它不会输入用户指定的单词。
int main(){
ifstream fin("wordlist.txt");
if (fin.fail()){
cerr << "Error opening the file" << endl;
system("pause");
exit(1);
}
vector<string> wordlist;
string word;
string out_word;
cout << "Please enter a word: ";
cin >> out_word;
fin >> out_word; //Trying to input the user specified word
//This inputs all the words
while (!fin.eof()){
fin >> word;
wordlist.push_back(word);
}
//This outputs all the words on the screen
for (int i = 0; i < wordlist.size(); i++){
cout << wordlist[i] << endl;
}
fin.close();
system("pause");
return 0;
}
【问题讨论】:
-
第一个
while (!fin.eof())应该是while(fin >> word) -
这是什么?仅仅查找如何写入/写入文件是否太难了。 cplusplus.com/doc/tutorial/files
-
投票结束:“这个问题是由一个无法再复制的问题或一个简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能以帮助未来的读者。通常可以通过在发布之前确定并仔细检查重现问题所需的最短程序来避免这种情况。”