【发布时间】: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 >out << EOT中,其中带有EOT的单行会触发输入的结束。)