【问题标题】:Looping error in C++ when trying to write to a file尝试写入文件时 C++ 中的循环错误
【发布时间】:2021-01-01 09:07:54
【问题描述】:

我正在用 C++ 制作一个极其粗糙的基于命令的文本编辑器。它在输出 .txt 的内容时工作得很好。但是写的时候就比较复杂了。将单个单词写入 .txt 时不会遇到问题,但在使用一个或多个空格写入输入时会出现此问题。首先我的代码是这样的。

#include <iostream>
#include <fstream>
#include <string>

int         readorwrite;
std::string filename;

int main() {
    while (true) {
        std::cout << "Read or write a file (1/2)" << std::endl << " > "; // note that the " > " is just a user input tag to make the program look cooler
        std::cin >> readorwrite;
        if (readorwrite == 1) { // what to do when reading
            std::string fileread;
            std::cout << "What file will you be reading?" << std::endl << " > ";
            std::cin >> filename;
            std::ifstream filename(filename);
            while (std::getline(filename, fileread)) {
                std::cout << fileread << std::endl;
            }
            filename.close();
        }
        if (readorwrite == 2) { // what to do when writing
            std::string filewrite;
            std::cout << "What will you name your file?" << std::endl << " > ";
            std::cin >> filename;
            std::ofstream filename(filename + ".txt");
            std::cout << "What will you be writing to the file?" << std::endl << " > ";
            std::cin >> filewrite; // this may be where the error occurs, if not then the next line
            filename << filewrite;
            filename.close();
        }
    }
}

假设我选择写作并且我的输入是NOSPACES,它没有遇到任何问题并正常回到开头。但是当我输入像YES SPACES 这样的东西时,似乎出了点问题,它开始重复循环开始的代码行?输出将是

Read or write a file (1/2)
 > Read or write a file (1/2)
 > Read or write a file (1/2)
 > Read or write a file (1/2)
 > Read or write a file (1/2)

它将继续非常快速地输出,而无需等待任何输入。有什么问题,我该如何解决?

【问题讨论】:

  • 使用 getline 而不是 std::cin 这可能会有所帮助:stackoverflow.com/questions/5838711/stdcin-input-with-spaces
  • 请看一下这个:operator<<,>>(std::basic_string)。在读取非空格后停止输入第一个空格是预期的行为。你打算如何评论输入结束?如果您只想阅读一行,std::getline() 可能是一种选择。如果你想阅读多行,事情会变得有点复杂。 (例如,您可以像在 shell 输入重定向中常用的那样使用结束标记,例如在 cat &gt;out &lt;&lt; EOT 中,其中带有 EOT 的单行会触发输入的结束。)

标签: c++ windows file


【解决方案1】:

两件事,

  1. 您应该将变量名从文件名更改为其他名称,因为很难解释您的意思。
  2. 您遇到的问题是 cin 忽略空格。更好的方法是使用 std::getline(std::cin, filewrite);这将一直读取到空终止 \0 或新行 \n。为了让它读取多行,把它放在一个while循环中。另一件需要注意的事情是任何无关的换行符。为避免这种情况,请为该字符串添加一个虚拟变量字符串和 getline,以确保它能够正确读取。

注意: 使用 std::cin,在读取之前另一个选项是放入 std::cin >> std::noskipws >> varname,但这有时可能具有未定义的行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2021-07-22
    • 2011-02-14
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多