C++ Comparing string to 0 using == operator? [duplicate] - c++

This question already has answers here:
No match for 'operator==' in a simple string code
(4 answers)
Closed 8 years ago.
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string A1;
cin>>A1;
if(A1==0)
{
cout<<"Success!";
}
else
{
cout<<"Failure!";
}
system("PAUSE");
return 0;
}
Beginner in C++. I`m trying to compare the value of a string keyed in to 0 using the == operator. Above is my sample of code. How do I solve this problem in the simplest manner? Thank you.

Consider writing if(A1 == "0"). The C++ std::string class overloads the == operator to allow this.
To check if the string is empty, write if (A1.empty()) or if (!A1.size()). I prefer the second formulation as it's consistent with other C++ standard library objects.
Personally I prefer to use the compare method on std::string instead. This makes your code more readable by other developers (e.g. Java developers would hate to see == in this context).

C++ is a strongly typed language. 0 by itself is a number. "0" is a string literal. There are functions which can do conversions, eg. std::stoi (String to Integer) and std::to_string (Lots of things to string), though.
So you have quite a few possible solutions here, to get the types equal. There's no real best solution for such a simplified case.

Related

Does std::string works only with 'std::cin' in c++ [duplicate]

This question already has answers here:
How to read and write a STL C++ string?
(3 answers)
Closed 4 years ago.
I've recently learnt about std::substr() by searching on Google. I saw a code something like this:
std::string s = "This is an example string";
std::string s1 = s.substr(11, 7);
std::cout << s1 << std::endl;
Now if I try to take input using scanf() function (instead of using std::cin), the program crashes during runtime. Doesn't std::string support using scanf() function?
scanf() belongs to a family of C functions that, being part of the C language rather than C++, offers no direct support for std::string and works instead with null terminated character strings.
If you are using C++, you should generally prefer std::string over null terminated terminated character strings and the input/output library over printf()/scanf() library functions.

Warnings and Errors with declaration of multi-character character

Screenshot 1
Here's my code.
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class Dragon
{
public:
char element[30];
int energy;
};
int main()
{
Dragon dragon;
char name[30];
cout<<"Enter element.\n\n";
cin>>name;
if(name=='Hell')
{
strcpy(dragon.element,"Hell Dragon");
dragon.energy=15000000;
}
else if(name=='Dark')
{
strcpy(dragon.element,"Dark Dragon");
dragon.energy=1000000;
}
else
cout<<"Unknown Dragon.";
cout<<"\nDragon's element = "<<dragon.element<<"\nDragon's energy level = "<<dragon.energy;
getch();
return 0;
}
Just tried this program on my own in C++ and have problems in fixing the following errors-
Errors and Warnings
If you do have an idea on how I can modify this, please help me out.
Thank you.
One cause of your issues is that == can't be used to compare contents of character arrays.
Solution 1: Use std::string
The std::string data type is the preferred data structure in C++ for text strings.
The std::string has overloaded == for comparing strings.
The std::string also has a find method for searching for a substring.
Solution 2: Use strcmp
The C language uses character arrays for strings. The C language also has str*() functions for processing character arrays.
The C++ language uses the str*() functions for processing the C-Style strings (character arrays).
Use strcmp to compare character arrays with string literals:
if (strcmp(name, "Hell") == 0)
You may also want to use strstr for finding substrings or strchr for finding characters in a character array (C-style string).

How To Compare Strings In C++?

I am just messing around in C++ with some things I recently learned and I wanted to know how to correctly compare two strings to each other. I looked at a previous thread for help, but I am not sure I am getting the variables right and there was a repeating error. (P.S. This is executed to the command prompt.)
string Users = "Username1";
//Set an empty string.
string UserChoice;
//Print out a line that warns the user to type a user.
std::cout << "Username: ";
std::cin >> UserChoice;
//If the user types out whatever "Users" is, run the code below.
if (strcmp(Users, UserChoice) == 0){
//Do Stuff
}
You want:
if (Users == UserChoice) {
The std::string class (well, really std::basic_string) overloads the == operator (and many others) to do what you want. You should not be using C functions like strcmp in C++ code, and in any case they cannot be directly applied to C++ std::strings.
Comparing strings is the same as comparing int values, char values, etc... . You should use the following method:
string a
string b
if (a == b)
{
// Do something
}
In your case, 'a' and 'b' would be replaced by 'Users', 'UserChoices'. But the basic format of comparing 2 variables of the same type stays the same regardless of the type (I'm not sure whether there are any exceptions to this rule or not).
It is also recommended, just as #latedeveloper mentioned, not to use c-language functions in a c++ program. The 2 languages are NOT interchangeable!
** Helpful tip: Always strive to keep your code as simple as possible. With some exceptions possible, the more complicated you make your code, the more hard you will make it for others to understand your code. To connect it to your case, why use a function strcmp() when you can keep it simple by using the == sign? This is just my 2 bits based on personal experience.
c style:
string a
string b
if(strcmp(a.c_str(),b.c.str()) == 0)

Comparing two strings in c++ issue.

Having this code:
char a[20]="wasd", b[20]="asd";
if((a+1)==b)
printf("yes");
Will not return "yes", even if "a+1" is "asd". I am wondering what am I doing wrong?
You need to use strcmp to compare C strings. == will just compare the pointers.
For example:
#include <string.h> // or <cstring> if you're writing C++
...
char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b)==0)
printf("yes");
By the way, if you're writing C++, you'd be better off using std::string. Then you could have simply used == to compare them.
If it's not a student assignment and you truly are using C++(as your tag says) you should use strings. Now you're using arrays and comparing arrays addresses instead of real strings. In a C++ way your code might look like:
#include <iostream>
#include <string>
int main()
{
std::string a ="wasd";
std::string b ="asd";
if(a.substr(1) == b)
std::cout << "Yes!\n";
}
Well, there is a better way to find if one string contains another but the code is a direct mapping of your C code to the C++-ish one.
You are actually comparing pointer addresses, not the actual string contents.
Your code should use strcmp:
char a[20]="wasd", b[20]="asd";
if(strcmp(a+1, b) == 0)
printf("yes");
Be careful that strcmp returns 0 if the strings are identical.
A better and more idiomatic alternative would be to use std::string:
std::string a = "wasd", b = "asd";
if(a.substr(1) == b)
std::cout << "yes";
substr does copy the string though, so it is slightly less efficient than the previous approach.
You have to use strcmp from string.h to compare strings.
if(strcmp(a+1,b)==0)
in Your case.
As per your code, when using (a+1)==b you are comparing the addresses of the pointers pointing respectively to second character of string 'a' and the first character of string 'b'.
It can work if you modify your code as:
char a[20]="wasd", b[20]="asd";
if(*(a+1)==*b) // now we are comparing the values towards which the
printf("yes"); // respective pointers are pointing
You can also use compare() for comparison of strings included in .

Nicely formatting numbers in C++ [duplicate]

This question already has answers here:
Representing big numbers in source code for readability?
(5 answers)
Closed 9 years ago.
In Ada it is possible to write numbers with underscores for separating digits, which greatly improves readability. For example: 1_000_000 (which is equivalent to 1000000)
Is there some similar way for C++?
EDIT: This is question about source code, not I/O.
As of C++14, you can use ' as a digit group separator:
auto one_m = 1'000'000;
Previous versions of C++ did not support this natively. There were two major workarounds:
Using user-defined literals in C++11; this would allow you to write code as follows:
auto x = "1_000_000"_i;
(Writing this as a constexpr would be trickier – but is definitely possible.)
Using a straightforward macro, which would allow the following code:
auto x = NUM(1,000,000);
There is no way to do this currently. There is, however, a proposal to introduce digit separators (N3499). They haven't yet chosen which character they'd like to use as a separator though. The current suggestions are:
Space: 4 815 162 342
Grave accent: 4`815`162`342
Single quote: 4'815'162'342
Underscore: 4_815_162_342
Unfortunately, they all have problems as described in the proposal.
You can take the hacky approach by using a user-defined literal:
long long operator "" _s(const char* cstr, size_t)
{
std::string str(cstr);
str.erase(std::remove(str.begin(), str.end(), ','), str.end());
return std::stoll(str);
}
int main()
{
std::cout << "4,815,162,342"_s << std::endl;
}
This will print out:
4815162342
It simply removes all of the commas from the given literal and converts it to an integer.
int main()
{
int x = 1e6;
}
you can always just define a variadic macro, used like N(123,456,678). it's a bit more trouble than it's worth, though. in particular, you may have to workaround some visual c++ peculiarities for portable code for counting arguments.
What you are looking for is perfectly possible by imbue()ing the I/O stream with the appropriate locale facet (in this case, num_put).
(This is assuming you are talking about I/O. If you are talking about the source itself, that is not possible as of C++11.)