0

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?

5
  • Is the line in the file "mmee hello hey"? Because if it is I see no reason why the two strings should match. Commented Jan 16, 2012 at 11:46
  • How do you tell that a no-op is not executed? Commented Jan 16, 2012 at 11:50
  • What do you mean by "this is never executed"? you mean return false, didn't reach the line of code, runtime error.... what? Also did you try debugging? Commented Jan 16, 2012 at 11:52
  • 2
    Have you tried debugging by printing the strings to compare to the screen? Use 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. Commented Jan 16, 2012 at 12:02
  • maybe you should post a minimal working sample of your code Commented Jan 16, 2012 at 12:03

4 Answers 4

1

Your code is correct.

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

Sign up to request clarification or add additional context in comments.

1 Comment

i had some problems with some permissions
0

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.

Comments

0

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/

2 Comments

(astring.begin(),astring.end(),' ') is there a space or no/
yes Their is a sapce ' '...Just check this link cplusplus.com/forum/beginner/863
0

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

1 Comment

Reasonable assumption, the three words were all on separate lines, just not indented, so they were rendered on one line before the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.