简体   繁体   中英

Convert char to int in 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM