BEGINNER TRAP! Console input - Accepting string including spaces (eg. address)

In the interests of passing information on - something that stuck me for QUITE a while, hopefully it can prevent someone else going through this heartache!
(EXPERTS - Please clarify/correct information if it is incorrect or not ideal - this is just what I have discovered works)

I have been using the following (exclusively) for accepting user input:
cin >> xyz

What I have discovered however is that this does NOT read spaces in strings. I was working on a program to accept a variety of data including an address. If you use cin, it will assign values after the space to future variables.
eg. For:
cin >> address;
entering an address of "123 something lane" will fill the 'address variable with "123", the next cin variable with "something" and the subsequent one with "lane".

The solution to this is using getline (cin, address);
One more important point - prior to using the above - ensure you have cin.ignore();

(Issue for me - I had something requesting a number, then getline was the next vairable input - the 'enter/return' marker was still in the cin stream and thus the getline command just grabbed that straight away instead of allowing me to input data.)

Funtional code now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int main(){
    int empl = 0;
    string f, l, p, a, c;
    double s;
    cout << "How many employees are there? ";
    cin >> empl;
    employee employees[2];  //THIS IS FOR TESTING - DONT WORRY - I WILL CHANGE TO DYNAMIC MEMORY ARRAY!!!
    for (int n=0; n < empl; n++){
        cin.ignore();
        cout << "First name: ";
        getline (cin,f);
        cout << "Last name: ";
        getline (cin,l);
        cout << "Phone number: ";
        getline (cin,p);
        cout << "Address in full: ";
        getline (cin,a);
        cout << "Enter comments (if nil, type 'n' then press enter): ";
        getline (cin,c);
        if (c == "n"){c = "";}
        if (c == "N"){c = "";}
        cout << "Enter salary : $";
        cin >> s;
        employees[n] = employee(f, l, p, a, c, s);
        }
    cout << "Printing employee data..." << endl;
    employees[0].printinfo();
    employees[1].printinfo();
    cout << endl;
    system("Pause");        
    return 0;
}



add:
The following is (seems like) a very good resource for people learning like me!
http://www.augustcouncil.com/~tgibson/tutorial/iotips.html
Last edited on
Topic archived. No new replies allowed.