Reputation: 11
I have an assignment that requires me to write a program that prompts the user to enter the name of a student and their grade and keeps looping until they enter "quit".
But I can't figure out how to get the user input for the array to get the entire line (which is a first & last name so I can't just do cin >> name1[i] since theres white space) but when I use cin.getline or just getline and compile it, I get an error message saying No member function matching getline.
Also when I compile it without getline, its just a continuous loop and doesnt let me input any info for name or grade. I'm new to arrays and cstring so please try to dumb down where I'm messing up. Thank you.
#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;
}
Upvotes: 0
Views: 2057
Reputation: 780974
Several issues:
char name1[50][MAXNAMESIZE];
. You just declared a single string.cin.getline()
requires a length
parameter to specify the maximum number of characters to input, so it doesn't overflow the buffer.strcmp()
, not ==
.>>
and getline()
, you need to call cin.ignore()
after >>
to skip past the newline. See cin and getline skipping inputCode:
#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;
}
Upvotes: 1
Reputation: 3305
Declare name1
variable as std::string
, Then just use std::cin
:
std::string name1;
std::cin >> name1;
But if you really need to get entire line you always can do:
std::string line;
std::getline(std::cin, line);
And then use the line.
If your assignment really requires that you use cstrings you can:
char line[50];
std::cin.get(line, 50);
Upvotes: 1