如何在C ++中的while循环中存储前一个迭代? [英] How do I store a previous iteration in a while loop in C++?

查看:134
本文介绍了如何在C ++中的while循环中存储前一个迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到类似标题的内容已被回答,但内容太密集,因为我不知道很多c ++。

I saw something with a similar title has been answered, but the content was too dense for me as I don't know a lot of c++.

我是非常新的编程,我不知道如何存储上一次迭代在我的while循环。我试图使用一个while循环将用户的文本写入一个文件,并结束他们的输入与两个 \\\
字符。这是我的问题是因为我的当前代码输入以一个实例enter结束。

I am very new to programming, I cannot figure out how to store the previous iteration in my while loop. I am trying to use a while loop to write a users text into a file, and end their input with two \n characters. This is where my problem is because with my current code the input ends with one instance of enter.

我的代码看起来像这样,但我知道 temp new_advice 是相同的:

My code looks like this, but I know temp and new_advice are the same:

char new_advice, temp;
while( (!(new_advice == '\n' + '\n'))) && (!(temp == '\n')) )
{
    temp = new_advice;
    cin.get(new_advice);
    fout.put(new_advice);
}

编辑*
好​​吧,我不认为我很清楚关于我在问什么。

Edit* Ok, I don't think I was clear about what I was asking.

原始作业说允许用户输入通知,以便它可以是任意长度的行。用户被告知要结束他或她的建议返回键两次,然后你的程序可以通过检查看到它连续两次出现字符'\\\
'的情况来测试它是否已经到达输入结束。

The original assignment said "Allow the user to type in advice so that it can be any number of lines long. The user is told to end his or her advice by pressing the return key two times. Your program can then test to see that it has reached the end of input by checking to see when it reads two consecutive occurrences of the character '\n'."

这是否会改变我的问题的答案?

Does this change any answers to my question?

我现在尝试使用以下代码执行此操作:

I have now tried to do this with the code:

char new_advice;
         int temp = 0;

         while(temp < 2)
         {
         if(new_advice == '\n')
         {
         temp = temp++;
         }
         cin.get(new_advice);
         fout.put(new_advice);

         }

但这不工作,我的程序不能识别输入结束程序。

But this is not working either, my program does not recognize enter as ending the program. Would the context of the whole program be worth posting?

推荐答案

我真的不想回答你的具体问题,因为习惯的方式做你想要的是相当不同,并且相当干净:

I don't really want to answer your specific question, since the idiomatic way of doing what you want is rather different, and quite a bit cleaner:

std::ofstream outfile("output.txt");

for (std::string line; std::getline(std::cin, line); )
{
    if (line.empty()) { break; }

    outfile << line << std::endl;
}

这篇关于如何在C ++中的while循环中存储前一个迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆