string text;
getline(text.c_str(),256);
1) I am getting an error “error: no matching function for call to ‘getline(const char*, int)”
What’s wrong in the above since text.c_str() also returns a pointer to array of characters.
If I write like this
char text[256]
cin.getline(text, 256 ,'\n');
it works fine. What’s the difference between cin.getline and getline?
2) How come
text string;
getline(cin,text,'\n')
accepts the whole line as the input. Where is the pointer to array of characters in this one?
text.c_str()returns a constchar *. You may not use it to modify the contents of the string, in any way. It only exists so that you can pass the string data to old C API functions without having to make a copy. You are not allowed to make changes because there is no way that the string object that holds the data could possibly find out about them, and therefore this would allow you to break the string’s invariants.Furthermore,
std::getlineaccepts completely different parameters. (You would know this if you took two seconds to type ‘std::getline’ into Google.) The error means exactly what it says: “no matching function for call” means “you can’t call the function with these kinds of parameters”, because every overload of the function accepts something different (and incompatible).std::getlineaccepts these parameters:There is not really any such function as “cin.getline”. What you are calling is the member function “getline” of the object “cin” – a global variable that gets defined for you when you
#include <iostream>. We normally refer to this according to what class the function is defined in – thus,std::istream::getline.std::istream::getlineaccepts these parameters:It does not need a stream parameter because it is a member function of the stream: it uses whatever stream we called it with.