Problems with the string library...

Write your question here.

Hi, I am a bit, no a huge novice in C++. I was just sifting through the tutorials, testing them out, that sort of stuff. I ran into this problem while I was trying out the (string) library.. thing... I don't know what to call it.

btw I am just testing out the formatting here, so please excuse the... fancyness

 
#include <string> 


That.
And when the user enters their (Location), the output is fine.
________________________________________________________________________

Let's say I enter Newbtown.
The output will say... Newbtown!

________________________________________________________________________

However! If there is a space within the entered text, such as...
________________________________________________________________________

I enter... Newb Town
The output will say... Newb!.

________________________________________________________________________

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 question1 = "What is your name?";
   string question2 = "Where do you live?";
   char name [20];
   char location [100];

   cout << question1 << endl;
   cin >> name;
   cout << question2 << endl;
   cin >> location;

   cout << "Hello, " << name << " from " << location << "!";
}
cin stops reading when it encounters the white space in between Newb and Town. Check into using getline in this situation.

http://www.cplusplus.com/reference/string/string/getline/?kw=getline


Edit:

And you can use string instead of character arrays too.

1
2
string name;
string location;
Last edited on
Thank so much for the quick response! Sorry if my questions are a bit too... simplistic. I am still just a budding programmer :3
Topic archived. No new replies allowed.