If statement is not working even statement is true - c++

My text file contain
Wew213
Wew214
Wew215
and my input in program is
Wew213
but it show me output
"Not Matched"
Actually what i am doing is i want to enter the input and if input match the number in a text file it should run the output by if statement otherwise else statement
here is my program
char file_data[10];
std::ifstream file_read ("D:\\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}

you are comparing the pointer value, which is different
you need to use strcmp to compare c string. or use std::string
if (strcmp(val, file_data) == 0)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
or
if (std::string(val) == std::string(file_data))
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}

The == test compares the addresses val and file_data. Instead of ==, to compare the contents of the character arrays use the function strcmp().

The given code,
char file_data[10];
std::ifstream file_read ("D:\\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
looks like this after running it through AStyle:
char file_data[10];
std::ifstream file_read ("D:\\myfile.txt");
cout<<"Enter the number to search"<<endl;
char val[10];
cin>>val;
while(!file_read.eof())
{
file_read>>file_data;
cout<<file_data<<endl;
}
if (val == file_data)
{
cout<<"Matched"<<endl;
}
else
{
cout<<"Not Matched"<<endl;
}
}
So, since the checking is done after the loop, checking only the last item read by the loop, even if you got the string comparison itself correct your program would not work.
The comparison doesn't work because, as others (rushing in) have already noted, you're comparing pointers, not strings.
To compare strings, use std::string instead of character arrays.
Minor correction: instead of
while(!file_read.eof())
write
while(!file_read.fail())
or just
while(file_read)
which calls fail for you (negating the result).
But doing this you would also have to check for success/failure of the input operation.
And the common idiom is to do that directly:
while( file_read>>file_data )

The == operator will simply compare the address. You will need to use strcmp function.

character arrays have no the comparision operator. So instead of comparing arrays theirself you are comparing addresses of first elements of the arrays.

Related

How can I compare C- string with C++ string?

I want to find out why compare function doesn't give me correct result ?
As I know it should return 0 if two string are the same!
bool validatePassword(char id[], string password) {
// cannot be the same as the id string
if(password.compare(id) == 0) {
cout << "password can not be as same as id\n";
return false;
}
return true;
}
As Matteo Italia mentioned in another answer's comment. Use the std::string's operator== like this:
bool validatePassword(char id[], string password) {
return password == id;
}
This function is really unnecessary because your caller should call operator== directly instead.
You can do it by converting id to a string and compare to strings:
string idStr(id);
if (password == idStr){
}
Or use strcmp to compare two char arrays:
if(strcmp (password.c_str(), id) == 0){
}
You have to convert the string to a char array with the method c_str()

Printing the first character in a given string which does not repeat

I am using the following function in c++ to return the first character in a given string which does not repeat,if not found return '#'.
char MyMethod(const char* str, int len){
int i,index=-1;
int *count = new int[256];
for(i=0;i<len;i++)
{
count[*(str+i)]=0;
}
for(i=0;i<len;i++)
{
count[*(str+i)]++;
}
for(i=0;i<len;i++)
{
if(count[*(str+i)]==1)
{
index=i;
break;
}
}
if(index==-1)
return '#';
else
return *(str+index);
}
this method looks fine, but it is always returning the first character of the string.
for example for the following string
aabcdd
it returns 'a' instead of 'b'.
I believe there has been a typo.
The statement :
if(count[*(str+i)]==1);
should not have been terminated:
if(count[*(str+i)]==1)
Remove the semicolon, so that the statements after the if condition are evaluated only when the condition is true.
Otherwise, the statements will be evaluated whatever be the result of if.

Writing an atoi to convert string to integer

I am writing an atoi to convert string to integer. Here is my code of atoi()function
int atoi(string str) {
int num=0;
int sign=1;
int len=str.size();
int i=0;
if(str[i]==' '&& i<len) i++;
if(str[i]=='+') i++;
if(str[i]=='-') {i++;sign=-1;}
for(;i<len;i++){
if(str[i]==' ') break;
if(str[i]<'0' || str[i]>'9') break;
if(INT_MAX/10<num || INT_MAX/10==num && INT_MAX%10<(str[i]-'0'))
{ return sign==-1 ?INT_MIN:INT_MAX;
break;
}
num=num*10+str[i]-'0';
}
return num*sign;
}
However, when input '1', output is 0, Why is that please?
well the code is kind of buggy:
this if(str[i]<'0' || str[i]>'9') break; won't get you very far; if you input 12aaa you want your method to return some error code or nothing, not the integer part of the string.
I don't even know what this is supposed to be....
if(INT_MAX/10<num || INT_MAX/10==num && INT_MAX%10<(str[i]-'0'))
{ return sign==-1 ?INT_MIN:INT_MAX;
break;
}
Get rid of the last if statement I highlighted, correct the first one so that the code does not try to convert anything other than valid integer strings, and the code should work.

String starts with a certain string

I have to write a program in which i ask the user multiple questions and if their answer starts with y consider it a true statement.
how can I write the string starts with statement
bool yes (string a)
{
string ans;
string begin = "y";
// compare the string to see if it starts with y
if(string begins with y)
return true;
else
return false
}
how can I do make that part I keep breaking my head trying to figure it out.
The simplest test would be to check if the string has a non-zero length, then look at the first character if it does:
bool is_yes(std::string const & str)
{
return !str.empty() && (str[0] == 'y' || str[0] == 'Y');
}
(Note that I take a reference-to-constant-string as a parameter instead of just a string. If the function accepts a string instead of a reference, the value of the string you pass to the function will be copied for no good reason.)
in C++
#include <string>
{
string a="hello"
if(a.front()=='Y')
return true;
else
return false
}

C++ See If Argument Is Numeric

I'm creating an encryption/decryption program in C++, and I use three user-provided numbers to customize the encryption. I read about isdigit() on cplusplus.com, and made a function based on that:
bool is_numeric(char *string)
{
int sizeOfString = sizeof(string);
int iteration = 0;
bool isNumeric = true;
while(iteration < sizeOfString)
{
if(!isdigit(string[iteration]))
{
isNumeric = false;
break;
}
iteration++;
}
return isNumeric;
}
However, it doesn't seem to work. Whether I give it a number, or a non-numeric character, it still returns false. What is wrong with my approach.
I think I'd use a standard algorithm:
bool is_numeric(char const *string)
{
return std::all_of(string, string+strlen(string),
[](unsigned char c) { return ::isdigit(c); });
}
Note that as it stands, your code can (often will) have undefined behavior (if the string contains anything that works out as a negative number when encoded into a char). This code prevents that by converting the char to an unsigned char as it's passed to the lambda -- that's why I used a lambda instead of just passing ::isdigit as the predicate to all_of.
You are computing the sizeOfString wrong. Try this instead.
bool is_numeric(char *string)
{
int sizeOfString = strlen(string);
int iteration = 0;
bool isNumeric = true;
while(iteration < sizeOfString)
{
if(!isdigit(string[iteration]))
{
isNumeric = false;
break;
}
iteration++;
}
return isNumeric;
}
You may want to add functionality to check for the . character as well! Right now your code only returns true if your string is an integer.
while ('0' <= *string && *string <= '9')
++string;
return *string == '\0';
or, if you prefer using isdigit:
while (is digit((int)*string))
++string;
return *string == '\0';
Another possible solution is using a stringstream:
bool isNumeric(const string& s) {
stringstream ss(s);
int val;
ss >> val;
return ! ss.fail() && ss.eof();
}
stringstream::operator>>(int&) will make the stringstream's failbit to be set if the given string is not numeric, and you need to check if all that's in the string is exactly one integer (and nothing else), so you also test for the eof bit.
This also works for negative numbers, and you can also change the int to double if you want to accept floating point numbers.