开发者

How to get a string input from a user in a char* in VC++?

开发者 https://www.devze.com 2023-03-08 18:59 出处:网络
I want to take a string as user input in my program.... ... char* name; ... printf(\"\\n\\tEnter a string : \");

I want to take a string as user input in my program....

...
char* name;
...
printf("\n\tEnter a string : ");
fflush(stdin);
//gets(name);
//gets_s(name,100);
//fget开发者_如何学Gos(name,100,stdin);
...

All the three ways of getting a string input are giving errors.Yes I can take a char array but my requirement is that input string could be of any length. How can I get my requirement fulfilled.

The 100 in gets_s/fgets is just to see whether these functions also complain or not.

I am using VS2010.

EDIT: I added visual c++ tag to show that I am using VC++ but my program is in C.

Thanks


Use std::string name; std::cin>>name;. C++ has much better string handling using std::string than fiddling with char*.


In C, there is no way if you want to handle "input string that could be of any length". You have to allocate enough memory to store the input; that is you have to specify maximum input characters your program wants to handle.

If you want to handle "input string that could be of any length", you can use C++ std::string, for example:

std::string stringOfAnyLength;
getline(std::cin,stringOfAnyLength); //read user line input (can be of any length)

And your example program is wrong, you should allocate enough buffer by a call to malloc first before you use name to get user input:

char* name;

name=malloc((MAX_LEN+1)*sizeof(Char));
...
printf("\n\tEnter a string : ");
fgets(name,MAX_LEN,stdin);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号