【问题标题】:File appending problem with users input with strings... C++用户使用字符串输入的文件附加问题... C++
【发布时间】:2020-10-19 02:26:24
【问题描述】:

我正在使用用户输入将字符串存储在 txt 文件中!但是我有一个问题。虽然输入用户字符串以进行文件写入很好,但我想添加新行,但是当用户为文件输入一个短语时,它会将输入写入文件,但不是在一个完整的行中,每个单词都需要一个线...

代码:

        int Char;

        std::string Input;

        std::ofstream ofDocument;
        std::ifstream ifDocument;

        ifDocument.open("Path\\Document.txt");
        ofDocument.open("Path\\Document.txt", std::fstream::app); //I tried ios::app but same result...

        if (ifDocument)
        {
                while (1)
                {
                    std::cin >> Input;

                    ofDocument << Input << std::endl;

                    switch (Char = _getch())
                    {
                        case '@':

                        std::cout << "You pressed '@', exiting application..." << "\n" << std::endl;

                        exit(0);
                    }
                }
        }
        else
        {
            std::cout << "Cannot create 'Document.txt'. Please retry..." << std::endl;

            ThisFunction();
        }

示例:用户输入:第一行:你好,我正在写一个文本文件

第二行:这行得通吗?

文件中的输出: 你好:新线 我:新行 上午:新线 写作:换行 在:新行 a : 新行 文本:新行 文件:新行 将:新行 这:新行 工作吗?

任何帮助表示赞赏!

【问题讨论】:

  • 您不应多次打开同一个文件。
  • 好吧...我只是想确保尽可能避免错误,但我可以看到...

标签: c++ io append fstream


【解决方案1】:

您应该尝试将 getline(std::cin, Input) 放在 std::cin >> Input 下方以捕获所有空格,这样它就不会在每个单词中都是一行。希望这有效

【讨论】:

  • 这行得通,但由于某种原因,getline 会自动出错并且不显示句子的第一个字符,谢谢!
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 2013-01-19
  • 2020-01-09
  • 2011-10-30
  • 2011-04-03
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
相关资源
最近更新 更多