Angel Dream
Angel Dream

Reputation: 411

compare a string with another string from a file c++

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?

Upvotes: 0

Views: 1336

Answers (4)

jrok
jrok

Reputation: 55395

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

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

Your code is correct.

Please check your input file to verify there is no leading or trailing spaces.

Upvotes: 1

mayur rahatekar
mayur rahatekar

Reputation: 4460

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/

Upvotes: 0

Ankit
Ankit

Reputation: 6980

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.

Upvotes: 0

Related Questions