how to print a multiple characters?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • arperidot
    New Member
    • Feb 2010
    • 11

    how to print a multiple characters?

    i have a really question that's been bugging me for a little too long now. so i want to print this, where 'grade' is a char

    Code:
     if(average >= 100) { grade = 'A+' ; }
            else if(average >= 90 && average < 100) { grade = 'A' ; }
            else if(average >= 80 && average < 90) { grade = 'B' ; }
            else if(average >= 60 && average < 80) { grade = 'C' ; }
            else if(average >= 50 && average < 60) { grade = 'D'; }
            else if(average < 50) { grade = 'F'; }
    everything works except for A+ which prints as +. what seems to be the problem here?
  • Adam01
    New Member
    • Aug 2008
    • 83

    #2
    Your storing 2 characters in one place.
    Where as ' ' can only hold one character.

    A quick fix would be to define grade as
    char grade[2];

    Then use grade[0] = 'A' for single grade letters, and then
    grade[0] = 'A';
    grade[1] = '+';

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      But be aware if you store grade as 2 characters

      char grade[2];

      Then you have exactly that, an array of 2 characters, both of which may or may not hold a value. You do not have a string because a string requires a zero '\0' terminating character and you do not have room in you array for one. To print this you will need to be something interesting using %c twice in a printf statement.

      However what you could do instead is declare an array of 3 characters

      char grade[3];

      and then actually store a string, it might only be a string of 1 or 2 characters but you would then be able to use %s to print it out regardless of the number of characters it contains.

      Of course you can't assign with = to a string (in C) so you would have to use strcpy.

      Comment

      • mush1578
        New Member
        • Feb 2010
        • 15

        #4
        u also write that if(avg>=100){
        cout<<"A+"<<end l;
        }
        it ll be better for u

        Comment

        Working...