Getting input from user using cin [duplicate]

自古美人都是妖i 提交于 2019-12-28 04:35:34

问题


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:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2184125/getting-input-from-user-using-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!