I am trying to compare a string from getline(file,line) with a std::string s="mmee" :
if (line==s){}
but this is never executed. why?? inside the file i have:
mmee
hello
hey
How to trim the spaces or enter from string line?
Your code is correct.
Please check your input file to verify there is no leading or trailing spaces.
First of all why do you think that will get executed.
as mmee hello hey is part of the same line in the file, when you do a getline line will contain the whole line and not just mmee. Hence the if condition would fail.
Look at this link for trimming spaces.
You can remove the space by using
std::remove(astring.begin(), astring.end(), ' ');
and after that you can compare the string.
check out the link:: http://www.cplusplus.com/forum/beginner/863/
You can compare to String : http://www.cplusplus.com/reference/string/string/compare/
std::getline() by default reads to the first new-line character. You can specify the character to which you want the function to read, like this:
getline(file, line, ' '); // not the space between single quote chars
This would read only "mmee" part of your example file (mmee hello hey).
EDIT: It is how I read your example. People who edited the OP just assumed that the input file is mmee\nhello\nhey
printf("'%s' == '%s'\n", line, s.c_str());so that you will see any leading or trailing spaces. Also compare string lengths to make sure all characters are printable.