[英]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;
}
幾個問題:
char name1[50][MAXNAMESIZE];
。 你剛剛聲明了一個字符串。 cin.getline()
需要一個length
參數來指定要輸入的最大字符數,因此它不會溢出緩沖區。 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.