comparing strings

I need some help comparing 2 strings
so if in a file there is the string ex: "hello world" and them the user inputs a string I need the program to tell me if the 2 strings are the same (are they both hello world)

so something like
1
2
3
4
5
6
  ifstream infile;
infile.open("whataver")
string f, u ;
getline(infile , f)
cin >> u;


I had tried
1
2

if(f == u)

it hadn't worked
can anyone help me out

Last edited on
It does work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main()
{
  std::string first_string = "hello world";
  std::string second_string = "second";
  
  std::string another_string = "hello world";
  
  if (first_string == second_string) std::cout << "first_string == second_string";
  if (first_string == another_string) std::cout << "first_string == another_string";
  if (another_string == second_string) std::cout << "another_string == second_string";
}

Last edited on
string equality is an exact binary match. That means case matters, spaces matter, and so on.
"hello" != "Hello" in c++.
" hello" != "hello" in c++.

the best way to see what is going wrong if the data "looks the same when I write it with cout" is to print the actual hex bytes of both strings to the console and compare that by hand. You will see why they are not equal when you do that, and can then back track how it got that way and what to do about it.


Ripb, you're using two slightly different methods to get input.
Your file is using getline, but your user input is using cin operator>>.

operator>> when used with streams is whitespace-delimited, so it's only storing the first word (hello).
Use getline for both places if you need to keep the whitespace.
Last edited on
@ Ganado
Yup the getline was the problem I have it working perfectly now ty sm :)
Topic archived. No new replies allowed.