How do I compare two integers in C++?
I have a user input ID (which is int) and then I have a Contact ID that is part of my Struct. The Contact ID is int also.
I need to compare to see if they are the same, to know that it exists.
I did something like this*:
if(user_input_id.compare(p->id)==0)
{
}
but I get an error message saying that expression must have class type.
*based on reading this page http://www.cplusplus.com/reference/string/string/compare/
The function you found is for comparing two std::strings. You don't have std::strings, you have ints. To test if two ints are equal, you just use == like so:
if (user_input_id == p->id) {
// ...
}
In fact, even if you had two std::strings, you'd most likely want to use == there too.
I am unsure what you mean, but IMHO
int k;
std::cin>>k;
if (k==p->id)
do_sth();
else
do_sth_else();
The point is you do not store input as string, but a int.
//simple program to compare
#include<iostream>
using namespace std;
typedef struct node {
int a;
}node;
int main() {
node p;
p.a = 5;
int a;
cin >> a;
if( p.a == a )
cout << "Equal" << endl;
else
cout << "Not Equal"<< endl;
return 0;
}
IF your struct's name is p and you have an integer in it called hello, you can do the following
int input;
cin << input;
if(input == p.hello){
cout << "the input is equal to p.hello" << endl;
}
else{
cout << "the input is not equal to p.hello" << endl;
}
Related
Unable to get the index from the second array to match the first array
// array constants
const int people = 7;
const int phoneNumbers = 7;
int main() {
char person, family;
int index;
string found;
int size =7;
//array declaration and set values
string people [] ={"Darryl","Jasmine","Brian","Duane","Ayana","Mia","Maya"};
// const char phoneNumbers = 7;
string phoneNumbers[] = {"678-281-7649", "818-933-1158", "212-898-2022",
"361-345-3782","817-399-3750","313-589-0460","818-634-4660"};
//set boolean value
found = "False";
//initialize index
index = 0;
// search variable and user input
cout << "who are you looking for? " << endl;
cin >> people[index];
for (index=0; index<=6; index--) {
if (people[index] == people[index] )
cout << "phone num for " << people[index] << " is "<<
phoneNumbers[index] << endl;
}
return 0;
}
When I put in Jasmine which is the people[] array, the phoneNumbers[] array brings back the first index of phoneNumbers[] which it should bring back the second index on phoneNumbers[] array
There are two problems here.
You are replacing content of the people[0] with the cin - so first item of the array will be always user's input.
You are decrement index, so the FOR cycle goes to the indexes 0,-1,-2... This is problem as arrays in C and C++ goes from 0 to upper values.
I would prefer to add one variable:
string input;
then:
cin >> input;
for cycle should be used:
for (index = 0; index < 6; index++)
and in your condition I would use:
if (person[index] == input) ...
A much cleaner way of doing this would be too use std::map provided by the C++ standard template library. Below is my take on what you're trying to achieve:
// phoneNumber.cpp
#include <iostream>
#include <map>
int main()
{
// delcare a map variable that maps people's names to phone numbers
std::map <std::string,std::string> lookUpPhoneNumber = {
{"Darryl", "678-281-7649"},
{"Jasmine", "818-933-1158"},
{"Brian", "212-898-2022"},
{"Duane", "361-345-3782"},
{"Ayana", "817-399-3750"},
{"Mia", "313-589-0460"},
{"Maya", "818-634-4660"}
};
// take input name
std::string inputName;
// user prompt
std::cout << "who are you looking for?: ";
std::cin >> inputName;
// look up name in map
if(lookUpPhoneNumber.find(inputName) != lookUpPhoneNumber.end()){
std::cout << "Phone num for " << inputName << " is: " << lookUpPhoneNumber[inputName] << "\n";
} else{
std::cout << "Name does not exist!\n";
}
return 0;
}
To compile and run, use the following command:
g++ -std=c++11 -o phoneNumber phoneNumber.cpp
./phoneNumber
Or check your compiler option to enable compiling with c++11 standard or higher.
I'm having a program to allow a user to enter 12 elements of type char initialized with the characters that form, eg "991231066245" and I would like to compare whether the 3rd element and 4 element is equal to 12.
For example:
char UserInput[20];
cout << "user input: ";
cin >> UserInput; //eg: 991231066245
//compare
int a = atoi(UserInput[2] + UserInput[3]); //something like this
if(a == 12){
cout << "yes";
}
But I able to get UserInput[0] & UserInput[1] by using UserInput[2]=\0
then user atoi(UserInput) to compare
If I add UserInput[4] = \0 then i will get 4 element so want to ask that is there any way to do? Thank you.
What about this:
if (UserInput[2] == '1' && UserInput[3] == '2')
{
std::cout << "yes\n";
}
If you have to convert to int, use std::string instead of char*, then it is very easy:
#include <iostream>
#include <string>
int main()
{
std::string UserInput{ "991231066245" };
int a{ std::stoi(UserInput.substr(2, 2)) };
std::cout << a << '\n';
return 0;
}
Output:
12
I have a function (int, string) in Main:
string word("HELLO");
int x = 0;
char choice;
swap(x, word);
I am trying, with no success, to pass into the following function:
void swap(int, string) {
int x = 0;
string word = "HELLO";
cout << "Would you like to change a letter? Please enter the letter
position. " << endl;
cin >> x;
if (x == 1) {
cout << "What do you want to change it to?" << endl;
cin >> word[0];
I keep getting this error:
Error C2664 'void std::swap(std::exception_ptr &,std::exception_ptr &) throw()': cannot convert argument 1 from 'int' to 'std::exception_ptr &'
What gives?
The main problem with your code is the indentation. Your code is not readable and mostly hard to comprehend it. Beautify it. Write nice, readable and a structured code. You can read more about indentation at the following link.
https://en.wikipedia.org/wiki/Indentation_style
The next thing is the function declaration. You do not declare your function before defining it. The function declaration should be top of the main function and definition of the function should be below the main function.
You can find more info about the function declaration at the following link:
http://en.cppreference.com/w/cpp/language/function
Since you are not using a char array to print out the string, it is useless to go through the string with a loop. Include the <string> library and start to work towards the string type. By passing the string variable inside std::cout is enough to print out the string.
Lastly, since you are trying to manipulate a string variable outside the main function, it is required that you are passing a reference parameter instead.
void myFunction(std::string& parameter);
This way, the original variable that exists inside the main or inside any other function will be altered. Without the reference, &, the value you are trying to modify will not be changed.
The following link demonstrates the use of reference.
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Please read my comments below of why some changes were applied. I made crafty changes to the change function. You are now eligible to work towards any
string type with any size.
#include <iostream>
#include <string> //When you are working on strings, use the string library.
using namespace std;
//Function declaration is very important. Have the declarations above main.
void change(string&);
int main() {
string word("HELLO");
char choice;
cout << "The word is : " << endl;
cout << word << endl;
//No need for the for loop to print out the string as
// we are working on a string and not a char array.
// for (int i = 0; i < word.length(); i++) {
// cout << word[i];
// }
change(word);
cout << "The new word is" << endl << word << endl;
cout << "Would you like to enter another change ? Enter Y or N ? " << endl;
cin >> choice;
if (choice == 'y' || choice == 'Y') {
change(word);
cout << word << endl;
}
else {
cout << "Good Bye" << endl;
}
system("pause");
return 0;
}
//When your datatype is to be modified outside the function, use the reference
//parameter type '&'.
//Without the reference type, your modified version of the type will only be modified
//inside that function.
//The original one will not be altered.
void change(string& word) {
/*
* size_t is simply unsigned int, to work towards manipulation and accessing
* of string types, use unsigned int or std::size_t
*/
size_t x = 0;
cout << "Would you like to change a letter? Please enter the letter position. " << endl;
cin >> x;
//Check to see if the inputted value is within the string length range.
if(x > 0 && x <= word.length())
cout << "What do you want to change it to?" << endl;
else{
cout << "The entered position is outside the string size range\n";
return; //Quit from the function if the condition is not met.
}
/*
* Instead of using if/else if statements,
* Just make a normal loop. Much simpler.
*/
for(size_t i = 0; i < word.length(); i++){
if((x-1) == i)
cin >> word[i];
}
}
The code I am using is:
#include <iostream>
using namespace std;
int reverse (int number){
int t = number, m = 0;
do
{
m = m*10 + t%10;
} while(t /= 10);
return m == number;
}
bool isPalindrom(int number){
bool Palindrom = reverse(number);
if(Palindrom == true){
return true;
} else {
return false;
}
return 0;
}
int main()
{
int number;
cout << "Please input a number " << endl;
cin >> number;
if(isPalindrom){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
}
The issue I am having is that isPalindrom is always evaluating to true. I believe it is because I am trying to set this up incorrectly. The program asks us to use the two functions bool isPalindrom(int number) and int reverse(int number). I'm just learning to use functions in C++ so i'm not to sure what I should do. Should I have reverse return the numbers flipped self (m) then in palindrom compare number to m and if it evaluates to true, it will return true. Then in the main check with an if statement to see if isPalindrom is true/false.
You are not calling the function correctly.
if(isPalindrom){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
To call it you have to supply a parameter like this
if (isPalindrom(number)) {
....
In your code isPlanindrom is (I believe, but actually it does not matter if I am right on this point) a function pointer and because it is in the condition of if it gets converted to a bool, which is true always.
PS: I just noticed that I was too fast in writing the answer. I just saw this one problem and didnt look at the rest of the code. It seems like you need to learn about very basics which would be too much to cover here in an answer. My suggestion: Get a book and rtfm :P
In main, you are evaluating the existence of a function called isPalindrom; you aren't actually calling the function. if(isPalindrom){ should become if(isPalindrom(number)){.
You forget to call isPalindrom with an argument. Here's the fix:
#include <iostream>
using namespace std;
bool reverse (int number){
int t = number, m = 0;
do
{
m = m*10 + t%10;
} while(t /= 10);
return m == number;
}
bool isPalindrom(int number){
return reverse(number);
}
int main()
{
int number;
cout << "Please input a number " << endl;
cin >> number;
if(isPalindrom(number)){
cout << "This is a Palindrom" << endl;
} else {
cout << "This is not a Palindrom" << endl;
}
}
I've also:
simplified your isPalindrom() function to a simple return statement;
set the return of reverse from int to bool.
You can try a LiveDemo
Short answer: you forgot to call isPalindrom.
Long answer: isPalindom decays to a nonnull function pointer, and nonnull pointers test true, this you always see the the if branch taken.
Also:
Yes, judging both by the name and the return type, reverse is intended to return the reverse of a number.
And correspondingly, it is the job of isPalindom to do the actual comparisons.
Furthermore, in most cases,
if (boolean) { return true; }
else { return false; }
should be replaced with
return boolean;
Finally, you really ought to be testing whether or not cin succeeded and your input is valid. (e.g. is the user allowed to enter 0? -73? Zero?)
I wrote a c++ code and used struct, I want to compare two string in struct type.but error occures:
#include <iostream>
using namespace std;
#define NumOfStudents 2
#define NumOfCourses 3
struct Student{
int stdnum, FieldCode, age;
double average, marks, res[NumOfCourses];
char Fname[20], Lname[20], cmp[20];
};
int main(){
struct Student students[NumOfStudents];
int i, j;
// char cmp[20];
cout << "\t **********************************************************************\n";
cout << "\t *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\n";
cout << "\t *+ FIRST-NAME || LAST-NAME || STUDENT-NUMBER || FIELD-CODE || AGE +*\n";
cout << "\t *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\n";
cout << "\t **********************************************************************\n";
for(i=0; i<NumOfStudents; i++){
cout << "STUDENT #" << i+1 << ": ";
cin >> students[i].Fname >> students[i].Lname >> students[i].stdnum >> students[i].FieldCode >> students[i].age;
}
cout << "what student do you want?[Enter family]\n";
cin >> students[j].cmp;
for(i=0; i<NumOfStudents; i++){
if(students[j].cmp == students[j].Lname){ //The error occurs here
for(j=0; j<NumOfCourses; j++){
cout << "\nCOURCE #" << j+1 << ": ";
cin >> students[j].marks;
}
}
else
cout << "The Student with name " << students[j].cmp << " doesn't exist!!!";
}
return 0;
}
In the code I commented place the error occurred...
thank you
Of course this comparison
if(students[j].cmp == students[j].stdnum){
is invalid because data member cmp has type char[20] and stdnum has type int. It is not clear what you are going to compare.
EDIT: I see you updated your post and wrote
if(students[j].cmp == students[j].Lname){
However this statement is also invalid because arrays have no the comparison operator. In this condition the both arrays are converted to pointers to their first elements and the pointers are compared. So the condition will be equal always to false. Instead you have to use strandard C function strcmp
if( std::strcmp( students[j].cmp, students[j].Lname ) == 0 ){
It would be simpler if you would use std::string instead of character arrays. You need to include header <string>
In this case the structure will look the following way
struct Student{
int stdnum, FieldCode, age;
double average, marks, res[NumOfCourses];
string Fname, Lname, cmp;
};
and you could use the comparison operator
if( students[j].cmp == students[j].Lname ){
This should do the trick for you.
if(strcmp(students[i].cmp, students[i].Lname) == 0)
If you are sure about using char string, you should use strcmp function to compare them.
(http://www.cplusplus.com/reference/cstring/strcmp/)
You are using a variable j which has no value assigned to it. Because of that, you are accessing an unknown member in the array, probably something off the array's boundaries (an index larger than NumOfStudents).
I think you want if(students[i].cmp == students[i].stdnum){ instead of if(students[j].cmp == students[j].stdnum){, still, it should be noted that you are comparing two char arrays, which does not have your intended effect of comparing the two strings. It will probably compare the position of the arrays in the memory(will always evaluate to false). Instead use strcmp, and use commands from the <cstring> library when dealing with cstrings (char arrays).
Or just save yourself the trouble and use the string class, which overloads the = operator and lets you compare two strings using =.