C++ 中的 char* 和 cin
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15319690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
char* and cin in C++
提问by Pepperwork
I would like to input a string of indefinite length to a char * variable using cin;
我想使用 cin 将不确定长度的字符串输入到 char * 变量中;
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"
你能不能告诉我怎么了”
回答by fredrik
Well, you havn't created an object for the char*
to point to.
好吧,您还没有创建char*
要指向的对象。
char* tmp = new char[MAX_LENGTH];
should make it work better (you have to define MAX_LENGTH). Another way to do this is:
应该让它更好地工作(你必须定义 MAX_LENGTH)。另一种方法是:
std::string strtmp;
cin >> strtmp;
const char* tmp = strtmp.c_str();
This method would mean that you need not use new
.
这种方法意味着您不需要使用new
.
回答by Martin York
Couple of issues:
几个问题:
char * tmp
cin >> tmp;
tmp is not allocated (it is currently random).
tmp 未分配(当前是随机的)。
operator>>
(when used with char* or string) reads a single (white space separated) word.
operator>>
(与 char* 或 string 一起使用时)读取单个(空格分隔)单词。
Issue 1:
问题 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).
如果您使用char*
并分配缓冲区,那么您可能无法分配足够的空间。读取可能会读取比缓冲区中可用的更多字符。一个更好的主意是使用 std::string (从这里你可以得到一个 C-String)。
Issue 2:
问题 2:
There is no way to read indefinite string. But you can read a line at a time using std::getline
.
没有办法读取不定字符串。但是您可以使用 一次读取一行std::getline
。
std::string line;
std::getline(std::cin, line);
char* str = line.data();