Search code examples
c++inputcharc-strings

read character array with cin.get


I try to write a program that get max to 20 characters and index them as character array then print out the array. The program compiles but the output are random words and symbols in place of the variable. Any idea why?

# include <iostream>

using namespace std;

int main ()
{
const int MAX = 20;
char str[MAX];
int index = 0;

while (index < MAX -1 &&
        (str[index++]==cin.get()) != '\n');

str[index]='\0';

cout<<"What i typed is _"<<str<<endl; 

return 0;
}

Solution

  • The condition un the while statement is invalid. There is a typo

    while (index < MAX -1 &&
            (str[index++]==cin.get()) != '\n');
                         ^^^
    

    Write

    while (index < MAX -1 &&
            (str[index++] = cin.get()) != '\n');
    

    Take into account that the new line character '\n' can be stored in the result string.