簡體   English   中英

循環以使用cstring數組c ++獲取用戶輸入

[英]Loop to get user input using cstring array c++

我有一項任務,要求我編寫一個程序,提示用戶輸入學生的姓名和他們的成績,並一直循環,直到他們進入“退出”。

但我無法弄清楚如何獲取數組的用戶輸入以獲得整行(這是一個名字和姓氏,所以我不能只做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;

}

幾個問題:

  • 對於C字符串數組,您需要char name1[50][MAXNAMESIZE]; 你剛剛聲明了一個字符串。
  • 讀入C字符串時, cin.getline()需要一個length參數來指定要輸入的最大字符數,因此它不會溢出緩沖區。
  • 您不需要名稱和等級的單獨循環。 獲得姓名后立即獲得每個學生的成績。
  • 要比較C字符串,你必須使用strcmp() ,而不是==
  • 混合>>getline() ,需要在>>之后調用cin.ignore()以跳過換行符。 請參閱cin和getline跳過輸入

碼:

#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;
}

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM