同时使用数组和字符串

Using arrays and strings together

本文关键字:字符串 数组      更新时间:2023-10-16

因此,我试图创建一个包含一些用户输入名称的数组,然后将这些名称与测试中的字母等级(例如:A、B、C、D、F)相关联。我的问题是,如何使用数组来接受用户输入的名称?

编辑:

对不起,这有点长,我不知道该放哪一部分会有帮助。完全是C++新手,我似乎在网上找不到任何关于这件事的信息,哈哈。

这是一些代码。该程序当前向用户询问测试分数,然后显示并降低最低测试分数,最后计算没有最低分数的分数的平均值。最终目标是向用户询问5个学生的名字,每个学生4个分数,然后去掉每个学生的最低分数,并计算输入的所有分数的平均值,而不考虑学生。

#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
    getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
    cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
    cout << "Score range must be from 0-100" << endl;
    cout << "Please re-enter a score: ";
    cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
    if (theArray[i] < lowest) {
        lowest = theArray[i];
    }
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
    sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}

#include <string> 尝试getline

std::string names[5];
for (int i = 0; i < 5; ++i){
    getline(std::cin, names[i]);
}