【发布时间】:2016-03-31 07:20:01
【问题描述】:
所以基本上我将从代码开始,我的问题写在下面。
string words = "";
fstream outFile;
outFile.open(name, fstream::out);
for (int i = 0; i < number; ++i)
{
getline(cin, words);
outFile << i << ": " << words << endl;
words == "";
}
number 由用户提供。
我想做的是创建一个文件,放置与数字一样多的记录,按顺序(从 0 开始)以每个记录的编号开始,然后将用户写入的文本放入控制台(它是通过 getline 放入“words”字符串中)。
不幸的是,我遇到了一个问题,因为对于冒号后的第 0 条记录,它会换行,实际上它开始从下一条记录复制文本。
为什么会这样?有人可以解释一下吗?
编辑:
#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>
using namespace std;
int main()
{
short int counter_of_commands;
string cmd = "";
string name = "";
cin >> counter_of_commands >> cmd;
if (cmd == "create")
{
string words = "";
int records;
cin >> name;
cin >> records;
fstream outFile;
outFile.open(name, fstream::out);
for (int i = 0; i < records; ++i)
{
if (i == 0)
getline(cin, words);
getline(cin, words);
outFile << i << ": " << words << endl;
words == "";
}
outFile.close();
}
return 0;
}
对于输入: 1
创建example.txt 3
示例 111 222
示例 1 333 444
示例 2 444 555
我明白了:
0:示例 111 222
1:示例 1 333 444
2:示例 2 444 555
【问题讨论】:
-
我想你会发现问题是你在读完数字后没有读换行符,所以你的第一个
getline实际上是在读数字后面剩下的内容。 -
您的代码没有什么特别的问题 - 看到它运行 here 并产生合理的输出。如果您可以调整该示例程序中的输入以显示发生了什么问题,我们将有一些东西要解释。或者,从控制台复制并粘贴全文,显示您输入的输入和输出文件内容。
-
@TonyD 我添加了一个 if 以省略该问题并编辑了原始帖子。
-
不确定
it creates a fourth row是什么意思。你的意思是最后有一个额外的空行?您可能会误解结果。将文件中的最后一个字符作为换行符对于文本文件是正确的。 -
@cooktheprogrammer:有可能,只是确保最后一条记录不要使用
endl。请注意,这是非标准的。见stackoverflow.com/q/729692/951890
标签: c++ string file cin getline