tags:

views:

177

answers:

3

I am using Turbo C++ 3.0 Compiler

While using the following code ..

char *Name;
cin >> Name;
cout << Name;

When I gave input with space ... its only saving characters typed before space .. like if I gave input "QWERT YUIOP" ... Name will contain "QWERT";

Any explaination why ??

+1  A: 

You just declared a character pointer that doesn't point at anything. You need to allocate space for your string. The most common method would be to allocate space on the stack, IE:

char Name[50];

Remember a char pointer by itself is just a place to put an address to where the real memory is. You still have to get a block of memory and store the address in your pointer. The code above creates an array of Names on the stack and you can use Name to store up to 49 chars plus a null terminal.

Alternatively, for variable length strings use std::string.

Doug T.
Given that his compiler is about 15 years old, it won't have `std::string` yet. You'd want a compiler from the 21st century for that.
MSalters
@MSalters lol good point. Didn't see the compiler :)
Doug T.
+2  A: 

You need to allocate space for the char array into which you want to read the Name. char *Name; will not work as it only declares a char pointer not a char array. Something like char Name[30];

Also the cin << only allows us to enter one word into a string (char name[30]).
However, there is a cin function that reads text containing blanks.

cin.get(name, MAX)  

get will read all characters including spaces until Max characters have been read or the end of line character (‘\n’) is reached and will put them into the name variable.

codaddict
cin.get leaves the delimiter ("\n") in the buffer which is not normally what you want. That's why it's generally better to use cin.getline(name, MAX).
Manuel
+3  A: 

When cin is used to read in strings, it automatically breaks at whitespace unless you specify otherwise.

std::string s;
std::cin >> noskipws >> s;

Alternatively, if you want to get a whole line then use:

std::getline(cin, s);

You'll also want to allocate storage for a raw char array, but with C++ you should use std::string or std::wstring anyway.

Peter Alexander
+1 for mentioning `getline`.
Jon Purdy
@Poita_: I don't think you understand how noskipws works. If you use "cin >> noskipws >> str" and the user enters "a b c", str will contain "a" and the rest of the input will be lost. getline() must be used if you want to read the whole text with whitespace.
Manuel