c++ - 在流 c++ 的文本之前有一个额外的换行符
问题描述
我正在尝试将用户输入文本复制到文件中,并且它只是在文本开始之前添加换行符,如何让它不这样做?
getline(cin, userInput);
while (userInput != endWrite) {
storyTime << userInput << endl;
getline(cin, userInput);
}
storyTime.close();
return 0;
}
解决方案
您的代码不完整,因此不可能绝对确定会发生什么——乍一看,我的直接猜测是您所看到的可能是您未引用的某些代码的结果。对于一种明显的可能性,您可能会询问用户要在其中编写输出的文件的名称:
std::string outputName;
std::cout << "Enter output file name: ";
std::cin >> outputName;
std::ofstream storyTime(outputName);
//...
在这种情况下,std::cin >> outputName;
读取文件名 - 但您必须按下enter键才能读取它,并且按下enter键将在输入中留下一个换行符,因此当您之后启动循环时,它'将被读取为用户之后输入的文本之前的换行符。
在旁边
除此之外,我通常会尝试使代码更简单一些:
while (std::getline(std::cin, userInput)) {
storytime << userInput << '\n';
}
作为一个非常普遍的经验法则,我建议从文本文件中读取的格式化(使用 anystd::getline
或 some operator>>
)作为 an , 或其他的if
条件while
。习惯性地这样做可以更容易地编写正确处理文件的输入循环。
演示
只是为了它的价值,这里有一些不插入额外换行符的工作代码:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string userInput;
std::string filename;
std::cout << "Please enter file name: ";
std::getline(std::cin, filename);
std::ofstream output{filename};
while (std::getline(std::cin, userInput)) {
output << userInput << '\n';
}
}
推荐阅读
- reactjs - 如何让 multer 将图像保存到磁盘?
- regex - 正则表达式 SSN 和税号组合
- android - A/libc:致命信号 11 (SIGSEGV),代码 2 (SEGV_ACCERR),tid 22188 中的故障地址 0x708d31bd64
- c# - 旋转对象以面对某个点,但仅在一个轴上
- javascript - Jquery,使用ajax发送默认值
- python - 通过一行代码使用 Flask 和 Python 在 Windows 10 本地托管 Web 应用程序 [已回答]
- android-studio - 如何制作第二个容器?
- python - 为什么我的 tkinter 框架没有填满整个窗口
- nestjs - TypeORM 是否支持自动级联删除?
- java - 加载多对多关系并映射到实体