[英]cin.getline() won't separate input according to spaces?
我一直在寻找问题的答案,但找不到。 我正在使用:
cout << "Enter student's first name and last name:\n";
cin.ignore(100, '\n');
cin.getline(name, 20, ' ');
cin.getline(family, 20, ' ');
但输入[例如:David Jones]不会分开,并且只能使用“名称”。
为什么getline()不使用分隔符分隔输入? 谢谢!
功能齐全:
//add a Student to Students.txt
void addStudent(fstream &f1)
{
//exception
if (!f1)
return;
int id;
char family[20];
char name[20];
bool courses[5];
cout << "Enter student's ID:\n";
id = getInteger(id, 1, 100); // id range: (1 <= id <= 100)
cout << "Enter student's first name and last name:\n";
cin.ignore(100, '\n');
cin.getline(name, 20, ' ');
cin.getline(family, 20, ' ');
cout << "Enter 0/1 for each of the student's 5 courses\n";
int boolean; // 0/1 input
for (int i = 0; i < 5; i++)
courses[i] = getInteger(boolean, 0, 1);
//find out if this id is already taken [=> return]
if (!f1)
throw "Error opening -Students.txt- from Project directory.\n";
if (isInFile("Students.txt", id))
return;
/*continue in case the opening was successful AND the id doesn't already exist*/
Student s(id, family, name, courses);
//write to our file
f1.seekp((id - 1) * sizeof(Student)); //(id-1): ids start from 1
f1.write((char*)&s, sizeof(Student));
}
我不明白你为什么叫cin.ignore(100, '\\n')
; 我觉得这让您感到困惑。
一个解决方案可以是,避免ignore()
,只需编写
cin >> name >> family;
但是,如果您想使用getline()
,我建议
cin.getline(name, 20, ' ');
cin.getline(family, 20, '\n');
否则,您必须在姓氏后面添加一个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.