Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

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 than character arrays. Should I then convert a character array to a string after retrieving input with cin.getline(), if that is possible?

like image 265
BrainPermafrost Avatar asked Sep 25 '11 23:09

BrainPermafrost


People also ask

Does Getline work with char arrays?

getline() Function and Character Array in C++ It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered. Must read the article getline(string) in C++ for more details.

Can you use Getline with CIN?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

What is the use of getline ()?

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.

How do you input a char array?

If you need to take an character array as input you should use scanf("%s",name), printf("%s",name); rather than using the %c . The %c returns the pointer to a character which cannn't be stored in pointer to character array.


2 Answers

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.

like image 58
FailedDev Avatar answered Sep 20 '22 03:09

FailedDev


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);
like image 42
R. Martinho Fernandes Avatar answered Sep 19 '22 03:09

R. Martinho Fernandes