【问题标题】:Why does getline(cin, string_name) creates an empty string the first time I use it in a loop?为什么 getline(cin, string_name) 在我第一次在循环中使用它时会创建一个空字符串?
【发布时间】: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


【解决方案1】:

你忘记;了吗?

for (int i = 0; i < number; ++i)

而不是

for (int i = 0 i < number; ++i)

编辑(来自 OP 的评论后):

嗯,这很好用:

int number = 3;

string words = "";
fstream outFile;
outFile.open("c:/test/test1.txt", fstream::out);
for (int i = 0; i < number; ++i) {
    getline(cin, words);
    outFile << i << ": " << words << endl;
    words == "";
}

但正如 Vaughn Cato 已经指出的那样,您可能正在阅读之前的换行符。

【讨论】:

  • 当然,我是偶然做的,因为有点晚,但一般分号在那里。
猜你喜欢
  • 2013-08-23
  • 2014-07-06
  • 2015-07-20
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多