someCoder
someCoder

Reputation: 185

Passing char pointer to cin and cin.get()

Making some simple exercises, I now have a huge doubt about iostream and pointers.

This is the 2 slightly different files I made (they both work):

File 1 receives an input as "My name is # Marco" and cout prints "Mynameis"

int main(){
using namespace std;
char* ch=new char[256];
int count=0;
cout <<"Enter chars, # to quit:\n";
cin >> ch;
while(*ch!='#'){
    cout << ch;
    ++count;
    cin >> ch;
}
cout << endl << count << " characters read\n";
return 0;
}

File 2 receives the same input as before, but this time cout prints the spaces too:

int main(){
using namespace std;
char* ch=new char[256];
int count=0;
cout <<"Enter chars, # to quit:\n";
cin.get(*ch);
while(*ch!='#'){
    cout << *ch;
    ++count;
    cin.get(*ch);
}
cout << endl << count << " characters read\n";
return 0;
}

What I don't understand is why in the second file at line 8 I have to write "cout << *ch" instead of "cout << ch" as in the first one. In fact, if I use "cout << ch" in file 2, all I get is a bunch of random symbols (characters taken from the pointer's address I guess)

Upvotes: 3

Views: 1365

Answers (1)

Greg Kikola
Greg Kikola

Reputation: 573

In the first case you are reading a C-style string into your array. That means cin is reading a string of characters at a time, and storing that character sequence in ch followed by a terminating null character \0. When you run cout << ch, cout will attempt to print the entire string, stopping when it hits the null character.

In the second case you are reading a single character and storing it in ch[0]. When you run cout << ch, cout thinks your char* is a C-style string, and it attempts to print the entire string, stopping only when it hits a null character. The characters after the first will probably be garbage values--whatever happens to be in memory. This is undefined behavior.

Note that in real code, you should be checking that your reads were successful. If your program encounters an EOF or an invalid input your loop will run forever. Also cin >> ch has a potential for a buffer overrun if the user enters too many characters. Better to use a std::string or the version of cin.get that takes a stream size argument.

Upvotes: 3

Related Questions