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

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()

Related

C++ converting char variable to string variable is returning ASCII value

My function looks like this:
string toOriginal(char c)
{
if (c == '$')
return "car";
else if (c == '#')
return "cdr";
else if (c == '#')
return "cons";
else
{
string t = to_string(c);
return t;
}
}
However, when my character c contains a value like 'r', I would like for it to return "r" as a string. However, it returns a string "114".
std::to_string does not have an overload that takes a char. It converts the char to an int and gives you the string representation of the int.
Use std::string's constructor.
string t(1, c);
You can also use alternative string constructor like this:
...
else
{
return std::string(&c, 1);
}
The method to_string() is for converting a numerical value to a string. A char is a numerical type.
See this related question on how to do it right: Preferred conversion from char (not char*) to std::string

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
}

If statement is not working even statement is true

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.

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.

Comparing two char* for equality [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the proper function for comparing two C-style strings?
My match condition doesn't work! Can someone advise how to compare to C-style strings?
void saveData(string line, char* data){
char *testString = new char[800];
char *stpr;
int i=0;
bool isData=false;
char *com = data;
strcpy(testString,line.c_str());
stpr = strtok(testString, ",");
while (stpr != NULL) {
string temp = stpr;
cout << temp << " ===== " << data << endl;
Even though temp and data match, the following condition doesn't work:
if (stpr==data) {
isData = true;
}
Not sure if this helps. The SaveData() function is called from the function below:
void readFile(char* str){
string c="", line, fileName="result.txt", data(str);
ifstream inFile;
inFile.open(fileName.c_str());
resultlist.clear();
if(inFile.good()){
while(!inFile.eof()){
getline(inFile, line);
if(line.find(data)!=string::npos){
cout << line << endl;
}
saveData(line, str);
}
inFile.close();
}
}
Since both stpr and data are C strings, you need to use strcmp():
#include <string.h>
...
if (strcmp(stpr, data) == 0) {
// strings are equal
...
} else {
// strings are NOT equal
}
This condition wont work because the == operator is not overloaded for char*.
if(stpr==data)
{
isData = true;
}
Use this instead.
if (strcmp(stpr, data) == 0)
{
isData = true ;
}
strcmp() returns 0 if both the cstrings are equal. Make sure that both the cstrings you are matching hold some legal memory and are null terminated at the end.
Edit:
To avoid any sort of hassle and bugs, it is advisable not to use raw char* and use std::string instead. So better make them strings and compare them.
std::string data ; //passed or declared as string
std::string stpr ;
.....
//Do some work.
if (stpr == data)
//do work here
This approach would save you a lot of troubles.
You are trying to compare two char*. YOu can try using strcmp(stpr, data) for checking the conditions.
Better use it like
if(strcmp(stpr, data)==0){..}