简体   繁体   English

C ++'\\ n'中断while循环

[英]C++ '\n' to break a while loop

I'm trying to write a program that will echo input chars to the screen using get() and put() until the user presses '\\n' '\\n' but it breaks with just one '\\n'. 我正在尝试编写一个程序,该程序将使用get()和put()将输入字符回显到屏幕上,直到用户按下'\\ n''\\ n',但它只中断了一个'\\ n'。 Thanks for your help. 谢谢你的帮助。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
    char ch1, ch2;
    do 
    {    
        cin.get(ch1);
        cout.put(ch1);
        cin.get(ch2);
        cout.put(ch2);
    } while ((ch1 != '\n') && (ch2 != '\n'));
}

You should use || 您应该使用|| instead of && 代替&&

int main()
{
char ch1, ch2;
do 
{    
cin.get(ch1);
cout.put(ch1);
cin.get(ch2);
cout.put(ch2);
} while ((ch1 != '\n') || (ch2 != '\n'));
}

You have turned your logic around. 您已经扭转了逻辑。

} while ((ch1 != '\n') && (ch2 != '\n'));

your here saying which i don't have a '\\n' and and not have a '\\n' but you do have a '\\n' so the first part is false and then the second clause is irrelevant as C++ short-circuit evaluation of || 您在这里说我没有一个'\\ n'并且没有一个'\\ n'但您确实有一个'\\ n',所以第一部分为假,第二部分与C ++短路无关||的评估 && expressions. &&表达式。

ie. 即。

false && something 

is always false. 永远是错误的。

Try using | 尝试使用| | | instead of &&. 代替 &&。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM