【问题标题】:Add more words to a text file in C++在 C++ 中向文本文件添加更多单词
【发布时间】: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 &gt;&gt; word)
  • 这是什么?仅仅查找如何写入/写入文件是否太难了。 cplusplus.com/doc/tutorial/files
  • 投票结束:“这个问题是由一个无法再复制的问题或一个简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能以帮助未来的读者。通常可以通过在发布之前确定并仔细检查重现问题所需的最短程序来避免这种情况。”

标签: c++ file text add words


【解决方案1】:

一个简单的处理方法:

  1. 将文件读入向量中
  2. 询问用户单词并添加到向量中
  3. 将向量的所有单词写到外流中。

【讨论】:

  • 在这种特殊情况下,我认为最好只使用字符串流,因为他们不会再次尝试访问/编辑单词。所以只需按原样添加它们就足够了
  • @Jidder:我不确定字符串流适合哪里。我只是表明,在许多情况下,read-modify-write 是处理文件而不是在代码中编辑文件的最简单方法。
猜你喜欢
  • 2019-04-28
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多