C ++中的char *和cin [英] char* and cin in C++
本文介绍了C ++中的char *和cin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用cin向char *变量输入一个不确定长度的字符串;
I would like to input a string of indefinite length to a char * variable using cin;
我可以这样做:
char * tmp = "My string";
cout << tmp << endl;
system("pause");
它完美地工作.
但是我无法做到这一点:
But I fail to do this:
char * tmp
cin >> tmp;
你能告诉我怎么了"
推荐答案
好,您尚未为char*
指向创建对象.
Well, you havn't created an object for the char*
to point to.
char* tmp = new char[MAX_LENGTH];
应该使它更好地工作(您必须定义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();
此方法意味着您不需要使用new
.
This method would mean that you need not use new
.
这篇关于C ++中的char *和cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文