Trying to compare to strings...
No matter what the strings are this program always reads them as different strings...
Code:
#include <iostream>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string1[20], string2[20];
cout<<"Input 2 strings. This program will tell you if the 2\n strings are excactly the same ";
cin.getline(string1, 20);
cout<<'\n';
cin.getline(string2, 20);
cout<<"The 2 strings you entered were "<<string1<<" and "<<string2<<'\n';
strcmp(string1, string2);
if(string1 == string2)
{
cout<<"The two strings you entered are the same";
}
if(string1 != string2)
{
cout<<"The two strings you entered are not the same";
}
system("PAUSE");
return 0;
}
Can someone explain why this isnt working and what i need to do to get it to work? Thankyou.
Re: Trying to compare to strings...
Code:
...
cin.getline(string1, 20);
cout<<'\n';
cin.getline(string2, 20);
...
here's a suggestion: use cin.get() and include the terminating character (usually '\n') for the string, so the string can be less than 20 characters. That way the person presses enter, the get() stops, and the next get() continues, and is reading on the next line....
Code:
...
cin.get(string1,20,'\n');
cin.get(string2,20,'\n');
...
I think that works... if it doesn't work properly, put a cin.ignore(1,'\n') in between the two cin.get().