is it possible to work this code w/out the char array?

As the title says, would I be able to do this if say, grade were a string ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main()
{
    string firstname;
    string lastname;
    char grade[4] = {'a','b','c','d'};
    int age;
    
    cout << "Please enter your first name: \n";
    getline(cin, firstname);
    cout << "Please enter your last name: \n";
    getline(cin, lastname);
    cout << "What letter grade do you deserve?\n";
    cin.getline(grade, 4);
    cout << "How old are you?\n";
    cin >> age;
    cin.get();
    
    cout << "Name : " << lastname << " , " << firstname << ".\n";
    cout << "Age : " << age << endl;
    grade[0] = ++grade[0];
    cout << "Grade : " << grade << endl;
    
    
    
    cin.get();
    cin.get();
    return 0;
}
I do think that you could not just redefine grade as a string, because ++ cannot take a string as an argument. At least, not unless you overload it.

You could possibly adapt the code to make it work for a string, though.

-Albatross
Agh, well I'm working with a book that asks to do replace all the char arrays with strings but I couldn't figure out the "grade" array. spent a lot of time on it.

the book is C++ primer plus 5th edition, if you've heard of it, the only problem is they don't make ALL solutions available online so I can't see the answer! Only a select few are available ):
Disregard my first post. ++ is defined for a character, so no issue there. The issue is somewhere else, and now I see where it really is. Bloody caffeine dependancy.

Also, I think they expect you to do a bit more than a simple change of type.

-Albatross
Last edited on
I'll post the problem, if what you expect is true, I will go back to the drawing board for this one.

"Write a C++ program that requests and displays information as shown in the following example of output:

What is your first name? Betty Sue
What is your last name? Yew
What letter grade do you deserve? A
What is your age? 22
Name : Yew, Betty Sue
Grade : B
Age : 22

Note that the pgroam should be able to accept first names that compromise more than one word. Also note that the program adjusts the grade downward, that is, up one letter. Assume that the user requests and A, a B, or a C so that you don't have to worry about the gap between a D and an F.

Write using the C++ string class instead of char arrays."
This is somewhat unrelated but...

grade[0] = ++grade[0];

This line of code is redundant. The ++ operator increments the variable by 1 by itself. After that you're just assigning the var to itself.

The above line could be shortened to either of the following:

 
++grade[0];

or
 
grade[0] += 1;
Topic archived. No new replies allowed.