2016-06-17 12 views
0

Ich habe nach einer Antwort auf meine Frage gesucht und konnte keine finden. Ich verwende:cin.getline() trennt Eingaben nicht nach Leerzeichen?

cout << "Enter student's first name and last name:\n"; 
cin.ignore(100, '\n'); 
cin.getline(name, 20, ' '); 
cin.getline(family, 20, ' '); 

aber die Eingabe [wie zum Beispiel: David Jones] nicht getrennt wird, und ist nur in 'Namen'.

Warum trennt getline() den Eingang nicht durch seinen Begrenzer? Danke!

volle Funktion:

//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)); 
} 
+0

[Works für mich] (http://ideone.com/YaI7bo) –

Antwort

0

Ich verstehe nicht, warum Sie cin.ignore(100, '\n') nennen; Ich denke, es verwirrt dich.

könnte eine Lösung sein, ignore() zu vermeiden, schreiben Sie einfach

cin >> name >> family; 

aber wenn Sie getline() verwenden wollen, schlage ich vor,

cin.getline(name, 20, ' '); 
cin.getline(family, 20, '\n'); 

sonst Sie ein Leerzeichen nach dem Namen hinzufügen.

+0

Vielen Dank :) – Yair