I have been trying for hours to find out whats wrong with this code but i cannot find it.
This code prints "No match" every time, even if string is the same as besmString.
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
char string[10];
char besmString[10]= "besm";
cin.getline(string,10);
if(string==besmString)
cout << "Match";
else
cout << "No match";
}
if you want a string then why use a char array? just use string instead
ex:
1 2 3 4 5 6
std::string str, besmStr = "besm";
std::getline(std::cin, str);
if(string == besmStr) //you could also do if(string == "besm") since you are setting the string to besm
std::cout << "Match." << std::endl;
else
std::cout << "No match." << std::endl;
@ Besm Osman: std::string is a data type from the C++ library, so please don't name your variables "string".
I have been trying for hours to find out whats wrong with this code but i cannot find it.
This code prints "No match" every time, even if string is the same as besmString.
In your case, you work with character arrays. Arrays decay to pointers, so when you do
if (string == besmString)
you compare the memory address of the first element of the string variable to the memory address of the first element of the beamString variable, and this is pretty much always false.
As giblit suggested, use the std::string type instead of char[]. That type supports "proper" comparison of contents with the == operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
int main()
{
std::string s1;
std::string s2("besm");
std::getline(std::cin, s1);
if (s1 == s2)
std::clog << "Match.\n";
else
std::clog << "No match.\n";
}
@Aceix
I changed the str into string but the code still wont compile.
Error 2 error C3861: 'getline': identifier not found
Error 3 error C2678: binary '==' : no operator found which takes a left-hand
Error 1 error C2039: 'getline' : is not a member of 'std'
yeah sorry I meant to do std::getline(std::cin, str) and not std::getline(std::cin, string) was looking at your code and didn't realize I typed string instead of str =p