循环以使用cstring数组c ++获取用户输入

时间:2018-04-11 20:07:08

标签: c++ arrays loops user-input c-strings

我的作业要求我编写一个程序,提示用户输入学生的姓名和成绩并保持循环,直到他们进入"退出"。

但我无法弄清楚如何获取数组的用户输入以获得整行(这是第一个和最后一个名称所以我不能只做cin>> name1 [i]因为theres white space)但是当我使用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;

}

2 个答案:

答案 0 :(得分:2)

几个问题:

  • 对于C字符串数组,您需要char name1[50][MAXNAMESIZE];。你刚刚声明了一个字符串。
  • 当读入C字符串时,cin.getline()需要length参数来指定要输入的最大字符数,因此它不会溢出缓冲区。
  • 您不需要单独的名称和等级循环。在获得他们的名字后立即获得每个学生的成绩。
  • 要比较C字符串,您必须使用strcmp(),而不是==
  • 当您混合>>getline()时,您需要在cin.ignore()后拨打>>以跳过换行符。请参阅cin and getline skipping input

代码:

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>

using namespace std;

#define MAXNAMESIZE 100

int main() {

    char name1[50][MAXNAMESIZE];
    int grade[50];

    for (int i = 0; i < 50; i++) {

        cout << "Please input a name (or 'quit' to quit): ";
        cin.getline(name1[i], sizeof name1[i]);

        if (strcmp(name1[i], "quit") == 0) {
            break;
        }
        cout << "Please input this person's grade: ";
        cin >> grade[i];
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    return 0;
}

答案 1 :(得分:1)

name1变量声明为std::string,然后使用std::cin

std::string name1;
std::cin >> name1;

但是如果你真的需要获得整条线,你总能做到:

std::string line;
std::getline(std::cin, line);

然后使用该行。

如果你的作业确实要求你使用cstrings,你可以:

char line[50];
std::cin.get(line, 50);