开发者

c++ char arrays, use in cin.getline()

开发者 https://www.devze.com 2023-04-07 04:24 出处:网络
I have the following code: char myText[256]; cin.getline(myText,256); Why exactly do I have to pass a character array to cin.getline() and not a string?

I have the following code:

char myText[256];
cin.getline(myText,256);

Why exactly do I have to pass a character array to cin.getline() and not a string?

I have read that in general it is better to use strings t开发者_StackOverflow社区han character arrays. Should I then convert a character array to a string after retrieving input with cin.getline(), if that is possible?


You are using the member method of istream. In this case cin. This function's details can be found here :

http://en.cppreference.com/w/cpp/io/basic_istream/getline

However you could use std::getline

Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. and you don't have to worry about the null terminating character and so on. Also it is possible to convert a char array to a string by using the appropriate string contructor.


That's an unfortunate historical artifact, I believe.

You can however, use the std::getline free function instead.

std::string myText;
std::getline(std::cin,myText);
0

精彩评论

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