Making new lines

Feb 13, 2011 at 10:44pm
Hi, I'm having a problem where, when I give the console a string with spaces, it makes new lines for each word. Here is the code:

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
#include "StdAfx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	string Location;
	int Gas = 100;
	cout << "Type where you want to go.\n>";
	getline(cin, Location);
	Gas = Gas - 10;
	while(Gas > 0)
	{
		cout << "You are now at " << Location << ", type where you want to go next.\n>";
		cin >> Location;
		Gas = Gas - 10;
	}
	if(Gas <=0)
	{
		cout << "You ran out of gas!\n";
		system("PAUSE");
		return 0;
	}
}


So, for example, if I were to type "your house" then the output would be:


You are now at your, type where you want to go next.
You are now at house, type where you want to go next.


How do I fix this?
Feb 13, 2011 at 11:21pm
cin >> Location;

You want to use getline() like you did on line 11.
Feb 13, 2011 at 11:29pm
As firedraco said. You get the trailing '\n' added on your string which makes those odd spaces.
Feb 14, 2011 at 12:22am

As firedraco said. You get the trailing '\n' added on your string which makes those odd spaces.


No i think the reason why it makes new lines is because "cin >> Location" only stores 1 word which make 2 entries when you inputed "(1)your (2)house"and by use of getline() as what firedraco has said, those 2 or more words will be stored at only 1 string.

Hope that helps
Topic archived. No new replies allowed.