char* and cin in C++

我只是一个虾纸丫 提交于 2019-12-19 04:15:07

问题


I would like to input a string of indefinite length to a char * variable using cin;

I can do this:

char * tmp = "My string";
cout << tmp << endl;
system("pause");

It works perfectly.

But I fail to do this:

 char * tmp
 cin >> tmp;

Could you give me a hing what's wrong"


回答1:


Well, you havn't created an object for the char* to point to.

char* tmp = new char[MAX_LENGTH];

should make it work better (you have to define MAX_LENGTH). Another way to do this is:

std::string strtmp;
cin >> strtmp;
const char* tmp = strtmp.c_str();

This method would mean that you need not use new.




回答2:


Couple of issues:

char * tmp
cin >> tmp;

tmp is not allocated (it is currently random).

operator>> (when used with char* or string) reads a single (white space separated) word.

Issue 1:

If you use char* and allocate a buffer then you may not allocate enough space. The read may read more characters than is available in the buffer. A better idea is to use std::string (from this you can get a C-String).

Issue 2:

There is no way to read indefinite string. But you can read a line at a time using std::getline.

std::string line;
std::getline(std::cin, line);

char* str = line.data();


来源:https://stackoverflow.com/questions/15319690/char-and-cin-in-c

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