basic stuff

This is my program:

#include <iostream>
Using namespace std;
Int main ()
{
String name, addr1, addr2, postalCode;

Cout << "Enter your name: ";
Cin >> name;
Cout << "Enter address 1: ";
Cin >> addr1;
Cout << "Enter address 2: ";
Cin >> addr2;
Cout << "Enter postal code: ";
Cin >> postalCode;

Return 0;
}

The problem I'm having is that when it compiles and I put my name as Mr S. Swanepoel, and go to next line it gives it as address 1: address 2: postalCode; in stead of
address 1:
Address 2:
PostalCode:

Can any1 help me to fix it?
cin reads as far as the white space, and leaves everything else in the buffer for the next read, so when you enter Mr S. Swanepoel

this happens:
1
2
3
4
5
6
7
Cin >> name; // reads in the Mr
Cout << "Enter address 1: "; 
Cin >> addr1; // Reads in the S.
Cout << "Enter address 2: ";
Cin >> addr2; // Reads in the Swanepoel
Cout << "Enter postal code: ";
Cin >> postalCode;


If you want to enter lines with spaces in, use getline.
Does getline work the same way?
after cout<<"Enter address \n"<<endl
Last edited on
closed account (zb0S216C)
Stephie22 wrote:
Does getline work the same way?

By same way, do you mean does it work the same way as std::cin? Not quite. std::istream::getline() extracts characters (including white-space) from the input buffer. It will keep extracting until either the specified number of characters have been successfully extracted, or until the newline character is found.

Wazzak
try this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;
int main ()
{
string name, addr1, addr2, postalCode;

cout << "Enter your name: ";
getline (cin,name);
cout << "Enter address 1: ";
getline (cin,addr1);
cout << "Enter address 2: ";
getline (cin,addr2);
cout << "Enter postal code: ";
getline (cin,postalCode);

system("pause");

return 0;
} 


and btw, you always start a new line with capital letters. such as Cin,Cout,Return.
Last edited on
thanx every1 for the help, i got it right, and works perfect now
Topic archived. No new replies allowed.