Convert char to int in C++ - c++

I am writing a GPA calculator program, and I want to change the value for a char to a different number.
For example if a user enters the letter a or A the value will be 4. This is what my program looks like. I know how to make it work if I use a switch cases, but I would like to do it this way.
char userInput;
char A, a = 4; // i want to change the value of A, a to 4
char B, b = 3; // i want to change the value of B, b to 3
char C, c = 2; // i want to change the value of C, c to 2
char D, d = 1; // i want to change the value of D, d to 1
char F, f = 0; // i want to change the value of F, f to 0
int count2 = 0;
int count3 = 0;
double gpa;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input valiation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
//line number 80 will add the values of the userInput together.
count2+=userInput;
// line 83 is a counter that holds the number of times the loop
// as excuted
count3++;
// line 88 will get a grade point average by dividing count3
// by count2
cout << fixed << showpoint << setprecision(2);
gpa = count2/count3;
} while(userInput !='X' && userInput!='x');
cout << "Total Grade Point: " << count2 << endl;
cout << "GPA: " << gpa << endl;
}
If my question is too vague please let me know so I can clarify.

If you look at ASCII table, you'll see that letters are just numbers.
http://www.asciitable.com/
You can calculate offset using simple subtraction:
'a' - 'a' == 0
'b' - 'a' == 1
'c' - 'a' == 2
and so on. To convert it to GPA grade you can do a simple conversion:
int deltaA = (int)('a' - 'a'); // explicit cast to int is not really needed
int max = 4;
int grade = max - deltaA;
Alternative solution would be to use a map:
std::map<char, int> grades;
grades['a'] = 4;
grades['b'] = 3;
grades['c'] = 2;
...
int score = grades['a']; // score == 4
It would be a good idea to stick with upper or lowercase letters. You can convert them using int std::tolower(int ch) and int std::toupper(int ch) functions. Putting char into int is ok - both are integers and int has wider range and char will fit.
The other way around - not so easy. int has wider range than char and you should check if your int value is in char range before converting back.

A couple of things...
char A, a = 4;
Creates character VARIABLES (storage locations) and assigns the variable a the value of 4. A variable represents a memory location, a place to store information. It is a human readable representation of this storage location. It is not a translation mechanism. The CHARACTER 'a' is a value represented by an ascii code that can be stored in the variable, hex value is 61 or decimal 97. Variable a is not the same thing as the character value 'a'. and storing a decimal 4 into a character variable is setting it to the EOT character.
Your best bet is to use the switch. It works fine.
It's best practice to initialize variables before you use them. Your counters will probably start out as zero, but depending on compilers, they may contain random values. Set them to zero before entering your loops.

Thank you guys for all the help. This is how I solved my problem. I meant to post it a while ago but just forgot.
char userInput;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
int count2 = 0;
double count3 = 0.0;
double gpa;
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input validation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
if(userInput !='X' && userInput !='x')
{
int grade=func(userInput);
// count2 will add the values of the userInput together
count2+=grade;
// count3 is a counter that holds the number of times the loop
// as execute.
count3++;
}
cout << fixed << showpoint << setprecision(2);
// to get the grade point avarage you need to divide count3 by count2
gpa = count3/count2;
} while(userInput !='X' && userInput!='x');
// the next few lines will display the information gathered
cout << endl;
cout << "Total Grade Points: " << count2 << endl;
cout << "GPA: " << gpa << endl;
cout << endl;
cout << endl;
}
return 0;
}
int func(char userInput)
{
// grade is being set to zero so there is a less chance of getting wrong
// data
int grade=0;
// this will make the userInput into a capital letter
userInput=toupper(userInput);
// we are setting value to equal the ascii number of the chosen
// letter
int value=userInput; // if input='A' then value = 65
// by subtracting 69 by the value it will help get us the point value
// we need.
grade=69-value; // gpa=4
// if the number value of grade becomes negative it will assign grade
// to store the number 0
if(grade<0)grade=0;
return grade;
}

Related

char + int to change the char value

I am new to C++, learned it for more than a month. I have a beginner-level knowledge of Python, like creating a list, modifying it, loops, etc. I don't know some codes for C++ that I know in python.
I am making a program for a school class (creative program). This is a part of my code (description at the bottom):
int number, new_one, num_letter;
char one;
cout << "You chose to encypher a message\nPlease choose an integer between 1-25:";
cin >> number;
cout << "How many letters are in your word?";
cin >> num_letter;
if (num_letter == 1)
{
cout << "Enter the first letter";
cin >> one;
new_one = one + number;
cout << "Your encrypted message is '"
<< static_cast<char>(new_one)
<< "' with the code number of "
<< number;
I am making a program where it enciphers and deciphers a message. The user chooses the number of letters of their message (maximum of 10 because I don't know how to use a for-loop in C++ yet). Then, they choose an integer. Then, they enter the letter, hit Enter, enter the letter, and hit Enter for the number of letters in their message (I don't know how to separate strings to chars in C++ yet).
When the user enters their letter and hits Enter, I cin >> that letter into the variable one, which is a char. Then, I add that one to the number the user chose, so the ASCII code of the one increases by the value of the number.
For example, when I enter 3 for number and h for the value of one, 104 (the ASCII code of h) should add up with 3, resulting in 107, which I then would static_cast to a char value.
But, when I add h and 3, instead of creating 107, it creates 155. Same for other variables. I tried cout'ing static_cast<int>(one) (in this case, the letter h) and number (which is 3). They printed 104 and 3.
But, when I add those two values, it prints 155. Why is this happening?
This is my solution. Hope it helps!
#include <iostream>
using namespace std;
int main()
{
int offset = 0;
int num_with_offset;
int size;
// Gets offset from user
do{
cout << "You chose to encypher a message\nPlease choose an integer between 1-25: ";
cin >> offset;
} while (offset < 1 || offset > 25);
// Gets letters in word
do{
cout << "Letters in word: ";
cin >> size;
} while(size < 0);
// Given size, init arrays
int number[size];
char one[size];
// Conversion from char to int
for(int i = 0; i < (sizeof(one)/sizeof(one[0])); i++)
{
cout << "Enter character " << (i + 1) << ": ";
cin >> one[i];
num_with_offset = one[i] + offset;
// Converts ASCII to integer and stores it into array
number[i] = static_cast<int>(num_with_offset);
}
// Prints out the new encrypted message
for(int j = 0; j < (sizeof(number)/sizeof(number[0])); j++)
{
cout << "Your encrypted message is: "
<< number[j] << " , with the code number: "
<< offset << "." << endl;
}
cout << endl << endl;
return 0;
}

IF or WHILE for numerical input checker

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

How to use a while loop with an array?

I've created a program that allows the user to enter 10 grades. I've used a while loop to store grades in the array, but if the user only has 5 grades to input, he can type done to exit the program.
After the loop has finished, it will then calculate and display. the highest grade, lowest grade, and the average grade within the array
Unfortunately, when the user types done, the program will display the rest of the grade lines that were not entered.
Can you help me find out how to stop the while loop from displaying the rest of unentered grades of the loop?
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int grade[SIZE];
int count = 0;
int lowestGrade;
int highestGrade;
bool done = false;
cout << "This program is limited to entering up to 10 grades." << endl;
while ( grade[count] != done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
}
//LOWEST GRADE
lowestGrade = grade[0];
for (count = 0; count < SIZE; count++)
if (grade[count] < lowestGrade)
{
lowestGrade = grade[count];
}
//HIGHEST GRADE
highestGrade = grade[0];
for (count = 0; count < SIZE; count++)
{
if (grade[count] > highestGrade)
{
highestGrade = grade[count];
}
}
//AVERAGE GRADE
double total = 0;
double average;
for (int count = 0; count < SIZE; count++)
total += grade[count];
average = (total / SIZE);
cout << endl;
cout << "Your highest grade is: " << highestGrade << endl;
cout << "Your lowest grade is: " << lowestGrade << endl;
cout << "Your average grade is: " << average << endl;
system("pause");
return 0;
}
Here are two problems with your code.
First:
....
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
....
The code above will attepmpt to read word "done" into integer variable, producing 0. Not what you want to do!
Second:
...
for (count = 0; count < SIZE; count++)
...
Code above will try to iterate over all possible elements (SIZE). However, you might have enetered less than that! You need to use count calculated in the previous loop as your boundary (and of course, use a different name for control variable in the loop).
There are a couple of things to unpack here.
Basically, the input you are retrieving is a char * and the >> operator is casting that to an int to fit into your array of grades.
Next what you are checking with grade[count] != done is if the integer in "grade" at the id "count" is not equal to the bool false. This will always return true in this case.
For your use case what you want to be checking is if your input is equal to the char * "done"
This cannot be happening in the predicate of the while loop because your grade array stores only int.
Therefore the simplest solution to the problem in my opinion, is to check whether the input is equal to "done".
If it is you want to set the done boolean to true
Otherwise we can try to cast it to an int and store that in the grades array.
Here is the revised loop:
while (!done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string input = "";
cin >> input;
if (input == "done")
{
done = true;
}
else
{
grade[count] = stoi(input);
}
count++;
}
The following is somewhat outside the scope of the question, but an additionnal advantage to using stoi() is that it ignores input that is not a number, which will shield against someone entering invalid input like "potato". This is why I immediately cast the input into a string.
Use another variable to store the amount ofgrades the user entered. You also cannot store a string in your integer array:
std::string input = "";
while(count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
getline(cin, input);
if(input == "done")
break;
try
{
grade[count] = std::stoi(input);
count++;
}
catch(std::invalid_argument)
{
cout << "not a valid number\n";
}
}
int actualsize = count;
and then use this variable to abort your for loops:
for (int i = 0; i < actualsize; i++)
There are two simple ways to solve your problem:
You can read strings instead of integers and in case the read string is "done", break the loop, else, convert the read string to an integer, something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string temp;
cin >> temp;
if(temp == "done") {
break;
} else {
grade[count] = stoi(temp);
count++;
total_count = count;
}
}
// rest of the code
```
If you don't want to use strings, then, assuming grades will be non-negative, you can stop reading input when the user types a negative number, say "-1". So, you will need to do something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or -1 to quit: ";
int temp;
cin >> temp;
if(temp == -1) {
break;
} else {
grade[count] = temp;
count++;
total_count = count;
}
}
// rest of the code
```
Also, don't forget to replace SIZE by total_count in rest of the loops i.e. the ones computing 'LOWEST GRADE', 'HIGHEST GRADE' and 'AVERAGE GRADE'.
NOTE: You will have to do #include <string> at the top as well, if you use the first option.

Program that finds Highest, Lowest, and Average of 5 number from an Array

My homework is to write a program that finds the highest, lowest, and average of 5 numbers in an Array that the user inputs. Here is my problem, the user does not have to enter all 5 numbers. But has to enter at least 2 numbers minimum.
I have the whole program done already I am having a problem with the beginning, below is my code where I am having a problem:
// Ask for name and explain program
cout << "Please enter your name: ";
cin >> name;
cout << endl;
cout << "Hi " << name << ", please enter up to 5 whole numbers." << endl;
cout << "I will find the HIGHEST, LOWEST, and AVERAGE number." << endl;
// Loop through users input
for (int i = 0; i < SIZE; i++)
{
cout << "Enter number " << (i + 1) << " : ";
cin >> number[i];
// Validate that the user has entered atleast 2 numbers
if (i >= 1 && i < 4)
{
cout << "Do you wish to enter another number (Y/N)? : ";
cin >> continue_game;
// Validate that the user only enters Y/N
while (continue_game != 'Y' && continue_game != 'y' && continue_game != 'N' && continue_game != 'n')
{
cout << "Please type in (Y/N): ";
cin >> continue_game;
}
// What happens if user chooses NO
if (continue_game == 'N' || continue_game == 'n')
{
i = 5;
}
// What happens if user chooses YES
else if (continue_game == 'Y' || continue_game == 'y')
{
i = i;
}
}
}
PROBLEM: If the user presses no after the 2nd number the remaining elements get a number asigned to them like : -8251616. Is there any way to make sure that the elements get assigned a zero or stay blank please help its due tomorrow and I can not figure it out.
SIZE = 5
Don't set i = 5 when the user says no. Just end the loop with a break; statement.
Also, the i = i; statement in the yes case is useless.
When you're getting the highest, lowest, and average values, make sure you only look at the values from 0 to i-1, so you don't access the uninitialized elemends of the array.
If you really want zeros you need to fill array with zeros:
int number[5] = {};
or
int number[5];
for (int i = 0; i < 5; ++i) {
number[i] = 0;
}
However this will give wrong output if the user enter less than 5 numbers. What you should do is to count how many numbers user entered and then use values from 0 to count - 1.
Advice, use break; instead of i = 5;.

Comparing Doubles and Chars in C++

I am trying to write a simple program in C++ that reads in an unspecified number of marks, then once the user inputs the character 'q', the program must calculate and display the average mark. However I am having some trouble. The approach I am taking is to save each value as a double, the I want to compare the double to the character 'q' and if they are the same character, end the loop, calculate and display the average.
However I think that the comparison between the char value 'q' and double value for the mark seem to be incomparable. This worked for me when I did the same using integer values for the mark but not doubles it seems. Any help would be appreciated.
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if (mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you'll need to change the mark variable to string, and then compare it to 'q', else try to parse is as a number.
otherwise this entire code, does not make a lot of sense, because 'q' in ASCII is 113, which I guess is a possible value
Typecast double to int and then compare, It must work because it compares ASCII value of character
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if ((int)mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you can not cast a double to char. You may need to use additional c++ library functions which convert string (char*) to double. There are different ways to do this.
Try this :
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
char userinput[8];
cin >> userinput;
std::stringstream ss;
double mark;
if (userinput[0] != 'q')
{
ss << userinput;
ss >> mark;
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "total : " << total << " count : " << counter << endl;
cout << "Average: " << average << endl;
return 0;
}
You are doing it wrong. If you try to cin a char into a double variable, the input char stays in the input buffer and the double variable remains the same. So this will end in an infinite loop.
If you really want the user to enter a char to end input, you need to take the whole input in a string variable. Check the string for q. If not present, use atof() to convert it to double.