C ++ char, use in cin.getline ()

I have the following code:

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

Why exactly do I need to pass an array of characters to cin.getline (), and not a string?

I read that in general it is better to use strings than arrays of characters. Should I then convert the character array to a string after receiving input using cin.getline() , if possible?

+7
source share
2 answers

You are using member istream method. In this case, cin. Details of this function can be found here:

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

However you can use std::getline

Uses a string instead of a char array. It’s easier to use a string, since they know their size, they automatically grow, etc., and you don’t have to worry about a null terminator, etc. You can also convert the char array to a string using the appropriate string constructor.

+4
source

This, unfortunately, is a historical artifact.

However, you can use the free function std::getline .

 std::string myText; std::getline(std::cin,myText); 
+4
source

All Articles