Kevin Sekeres
Kevin Sekeres

Reputation: 1

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'. 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'));
}

Upvotes: 0

Views: 95

Answers (3)

Gimballock
Gimballock

Reputation: 477

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'));
}

Upvotes: 2

Ritesh
Ritesh

Reputation: 67

Try using | | instead of &&.

Upvotes: 0

Surt
Surt

Reputation: 16099

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 || && expressions.

ie.

false && something 

is always false.

Upvotes: 1

Related Questions