comparing two strings

This program is supposed ask the user to input two phrases and return whether they are the same or not. It's working for a single word, but for some reason it stops checking if it hits a space. Can figure out why. I Thought getline was supposed to take in spaces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  #include <iostream>
#include <string>
#include <iomanip>

using namespace std;

string inputOne; // user's first input
string inputTwo; // user's second input

bool misMatch = false; //to determine if a misnatcg pair is found

void compare (string inputOne, string inputTwo, bool misMatch);

//main function asks user for two inputs
int main () {

    //ask the user to type the first string
    cout << "Please type a word: " << endl;
    getline (cin, inputOne); //store the entered phrase in string inputOne

    //ask the user to type the second string
    cout << "Please retype the word exactly: " << endl;
    getline (cin, inputTwo); //store the entered phrase in string inputTwo

    compare(inputOne, inputTwo, misMatch);

return 0;
}

/*******************************************************************************
compair funtion compares the two inputs and returns true or false to the
main function
*******************************************************************************/
void compare (string inputOne, string inputTwo, bool misMatch)
{
    if (inputOne.length() == inputTwo.length())
    {

        int i; //integer to hold the value of character being checked

        // loops through each character in the input
        for (i = 0; i < inputTwo.length(); i++)
        {
            //check each character in string one to string two
            if (inputOne.at(i) != inputTwo.at(i))
            {
                cout << "The inputs DONT'T match." << endl;
                return;
            }
        }
    }

    cout << "The inputs match." << endl;
}


Please type a word: 
hello 
Please retype the word exactly: 
hello o
The inputs match.

Last edited on
The problem comes from they two strings don't match length, so the if-statement block of code from lines 37-51 never execute and the program subsequently jumps to line 53 and outputs that the inputs match. You need to reposition line 53 to inside the if-statement after you've checked all the letters. That way it will only execute if the two strings are the same length AND all letters match.
Why all the logic in your "compare" function. Your using C++ strings why not either use the comparison operator== or the std::string.compare() function?

Topic archived. No new replies allowed.