反转用户输入字符串数组c ++的2个字

时间:2018-04-12 01:01:07

标签: c++ arrays string function compiler-errors

我正在做一项任务,希望我让用户在循环中输入学生姓名和成绩,直到他们进入“退出”状态。然后,使用名为FormatName的函数将每个名称和等级的结果显示在屏幕上,该函数使用const字符串参数。用户输入的名称格式假定为“First Last”,我必须使用该函数将其重新格式化为“Last,First”。

但我一直在我的函数中收到错误消息,我无法找出正确的方法。我想读取array [i]的元素,将它存储在lastfirst中,然后反向打印并打印等级[i]。

如果您能提供有关我应该采取何种方法的指导,请告知我们。

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <iomanip> // only way xcode will let me use setfill and setw

using namespace std;

string FormatName(const string name1);
int main() {

    //variables
    const int CAPACITY = 50;
    string name1[CAPACITY];
    string grade[CAPACITY];
    char quit[]= "quit";
    int i;

    // loop to continue prompting user for name & grade if quit not entered
    for (i = 0; i < CAPACITY; i++) {
            cout << "Please input a name (or 'quit' to quit): ";
            getline(cin, name1[i]);

        //if quit, break
        if (name1[i].compare(quit) == 0) {
            break;
        }
        //continue loop and ask for grade if not
        cout << "Please input this person's grade: ";
        cin >> grade[i];
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    //if statement to not print chart to screen if no data entered
    if (name1[0].compare(quit) == 0) {
        cout << "\nYou did not enter any students." << endl;
        cout << "Goodbye!" << endl;
        return 1;
    }

    else {
    //display class scores to screen
    cout << "\n\nClass scores:" << endl;
    cout << setfill('-') << setw(60) << "-" << endl;

    cout << setfill(' ');
    cout << setw(50) << left << "\nName" << right << "Grade " << endl;
    cout << setfill('-') << setw(60) << "-" << endl;

    //call function with for loop to print each element 
    for (int j = 0; j < i; j++)
            FormatName(name1[i]);

    cout << '\n' << setfill('-') << setw(60) << "-" << endl;
    }
    return 0;
}

string FormatName(const string name1)
    {
    string lastfirst;
    int i;

    //set lastfirst equal to the first element of name array
    lastfirst = name1[0];

    for (string el &: lastfirst) // 2 errors saying "Expected ';' in 'for' 
                                 // statement specifier" & "Expected 
                                 // expression"
        cout << el << ',';

    //more code to make lastfirst[i] print to screen. 
    return lastfirst[i]; //error for obvious reason, I'm still working on it
    }

编辑:

我稍微更改了一下这个函数以测试它打印到屏幕上的内容,但是当我返回值时它根本没有打印出来,或者当我输出&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; lastfirst。知道如何让它返回name1而不是退出吗?

  string FormatName(const string name1)
    {
    string lastfirst;
    int i = 0;

        lastfirst = name1[i];
    //set lastfirst equal to the first element of name array
        cout << lastfirst;

    //more code to make lastfirst[i] print to screen.
    return lastfirst;
    }

0 个答案:

没有答案