【发布时间】:2018-09-21 20:18:09
【问题描述】:
我有一个作业,要求我编写一个程序,提示用户输入学生的姓名和他们的成绩,并不断循环,直到他们输入“退出”。
但我不知道如何获取数组的用户输入以获取整行(这是名字和姓氏,所以我不能只做 cin >> name1[i] 因为有空格) 但是当我使用 cin.getline 或只是 getline 并编译它时,我收到一条错误消息,说没有匹配 getline 的成员函数。
此外,当我在没有 getline 的情况下编译它时,它只是一个连续循环,不允许我输入任何名称或等级信息。我是数组和 cstring 的新手,所以请尽量减少我搞砸的地方。谢谢你。
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main() {
const int CAPACITY = 50;
string name1[CAPACITY];
string grade[CAPACITY];
char quit[]= "quit";
int i;
//for loop to get names and grades from user until quit is entered
for (i = 0; i < CAPACITY; i++) {
while (name1[i] != quit)
cout << "Please input a name (or 'quit' to quit): ";
getline(cin, name1[i]);
//break if name1[i] = quit
if (name1[i].compare(quit) == 0) {
break;
}
//continue loop if quit not entered and get the grade from that person
cout << "Please input this person's grade: ";
cin >> grade[i];
}
return 0;
}
【问题讨论】:
-
name1不是字符串数组,而是char的数组,也就是一个字符串。 -
不能使用
==比较C字符串,必须使用strcmp()。 -
看来您需要学习 C 字符串如何工作的基础知识。如果你需要一个包含 50 个字符串的数组,它应该是
char name1[50][MAXNAMESIZE]; -
@Barmar 是的,这是我的错误,我刚刚修复了它。我只是重新阅读了说明,它说用 CAPACITY 设置最大值,但它没有告诉我该容量应该等于多少。我现在正在处理 strcmp 函数
标签: c++ arrays loops user-input c-strings