Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
If each of these string variables in the left portion certainly contain their literal equivalents in the latter, then why do I not get my message?
if (make_tuple(this->currentState, inputSymbol, stackTop) == make_tuple("q0", "a", "0"))
cout << "These tuples are equal" << endl;
The reason I ask is because I am using a map with a tuple as the key and when I try to use find(), it behaves as if the key does not exist in the mapping, which I am certain it does because I went through the map using an iterator and displayed all of the keys (each element in the tuples). I suspect that the error has something to do with the above code because those should be equal but they are not. (I am using map.find(make_tuple(blah, blah, blah)) and comparing that to the map.end()) Thoughts?
Here's my best guess at your question:
const char input[] = "hello";
if (std::make_tuple(input) == std::make_tuple("hello")) {
// won't get here
std::cout << "equal\n";
}
The reason is that tuple<>::operator== is just element-wise equality. In this case, we have two tuple<const char*>, but while the strings they point to are the same, the actual pointers themselves are different, and we're just comparing the pointers.
If you want this to work, you'll need the left-hand-side to be a type that has an operator== that does the right thing. Like, say, std::string:
const char input[] = "hello";
if (std::make_tuple(std::string(input)) == std::make_tuple("hello")) {
// now it happens
std::cout << "equal\n";
}
Or, since you're using a std::map, you will not want to use the default tuple<>::operator< and instead provide your own that uses strcmp instead of the raw pointer <.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to write a programm that reads the surname introduce and gives back the info of the student (birthdate, group, etc). The compiler does not recongize the == operator, I guess it doesnt know what to compare, either the address or the value?(I would appriciate an explanation)
I read similar cases and they suggest to use bool operator. As far as I know bool operator just returns true or false(I dont see the way to use it to print the students info)
Also I was considering usind char or using strcmp (srting functions for comparing).
void find_fam ( struct st student[], int length, string & fam)
{
for(int i=0; i<length; i++)
if ( student[i]== fam[i]){
cout << "Student:\n"<< student[i].imia << student[i].otchestvo << student[i].familia <<
student[i].gruppa << student[i].grozhdenia);
}
}
If you have a struct like this for example
struct st
{
std::string name;
int age;
};
Then you would want to compare the fam to that member of your struct
if (student[i].name == fam)
So now .name is the corresponding std::string that you are trying to compare. Otherwise you are trying to compare a std::string to a st struct.
In this example you've shown, you're comparing an entire instance of the struct to the string, which is invalid.
What you should do is compare the string attribute to the string you take in.
Assuming the family of the student is called family and is of type string:
if(student[i].family==fam)
{
//statements
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Let's take the following code for example
int number = 1;
char * charsequence = (char *)&number //casting the address of number to char *
std::cout << charsequence << endl;
The above snippet produces the following result:
☺
If I change the number then a different symbol appears.
That's fine, the real question is why do I always get the same symbols even though the memory location (&number) is different on each run? And the most important part is why do I get symbols instead of my memory address?
I assume that the casting I did is not working as I thought it was.
Edit: Since it's closed as unclear of what I'm asking, here's there real question:
How do i print the memory address of an object to the console?
At the time of this edit, this question was already answered. See the accepted answer
std::ostream has a special overload for operator<< which, when you give it a char *, will not print the value of the pointer, but instead assume that you gave it a pointer to the first element in an array of characters that is null-terminated, and then try to print the entire array up to the terminator. (This overload allows you to print C strings in a sort-of natural looking syntax.)
Since your pointer does not in fact point to the first element of a null-terminated array, your program has undefined behaviour.
If you want to print the pointer value, you should use a void pointer:
std::cout << static_cast<void*>(&number) << "\n";
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am implementing linked list in c++. In that am trying to compare a data stored in the node with a string. Here is my code:
String f;
cin>>f;
if(strcmp(temp->data,f)==0)
{ cout<<"same"; }
else
{ cout<<"not same"; }
Here is my error:
"assignment1.cc", line 160: Error: Cannot cast from std::string to const char*.
"assignment1.cc", line 160: Error: Cannot cast from std::string to const char*.
How to compare those two strings?
If you only need to check for equality, you can simply use operator== to compare two strings. In your case, that seems to be:
if (data->temp == f)
However, if you want the functionality provided by strcmp (that is, if you need to know which string is larger lexicographically in case they are not equal), you can use string::compare:
if ( s1.compare(s2) < 0 )
You can use the std::string::c_str method:
std::string f;
cin>>f;
if(strcmp(temp->data,f.c_str())==0)
cout<<"same";
else
cout<<"not same";
You can either use f's "compare()" operator (http://en.cppreference.com/w/cpp/string/basic_string/compare) or you can use operator ==
#include <iostream>
#include <string>
int main() {
std::string f("hello world");
const char* p = "hello world";
if (f == p)
std::cout << "f == p" << std::endl;
}
See http://ideone.com/TTXRZv
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm beginning in C++ and I have a simple task. As title said, I want to delete first and last character from a string for x times (where x is the lenght of the string). For example, if the string is "example", the result will be:
example
xampl
amp
m
amp
xampl
example
So far, I'm thinking like this:
#include <iostream>
#include <string>
string sir = "Example";
int len, i;
len = sir.length();
for(i=1; i<=len; i++)
{
sir.erase(sir.begin(), sir.end());
cout<<sir;
}
Or something like that... Can someone help me ?
You want to delete both the first and last char.But in the example you also added them each step. It is not actually clear what you want. Whatever you want to delete or add the characters it is feasible to keep the string unchanged. So you should use substr. Check it out here.
The problem is that
you can not use std::string::erase with integral index such as int i,
you need to use std::string::iterator
but even if you use std::string::iterator, with the current logic you would be trying to increment an iterator after the erase has been called. (such iterator is invalid)
Possible solution: assign sir.begin() to your iterator after each erase.
Here's how it could look like:
std::string sir = "Example";
for(string::iterator i = sir.begin(); i != sir.end(); i = sir.begin())
{
sir.erase(i);
std::cout << sir << std::endl;
}
outputs:
xample
ample
mple
ple
le
e
Just note that after erasing characters from your std::string, these characters are lost. You can not "restore" them. For the other half, you'll have to come with more sophisticated approach, but I'll leave that to you :)