Allow a string to accept spaces?

Oct 26, 2009 at 12:07pm
Hi there.

I just worked out how to use strings a little thanks to this forum. I was wondering though, if it is possible to have a string array(?) accept spaces?

For instance:

I've included the string library. Now, I declare the array "items".

string items[20];

Can I have it so that a "cout<<items[0];" line will accept the words BLUE CHEESE? I noticed that it will accept one word but not two words separated by spaces when put in a while loop.

Any help would be appreciated.
Oct 26, 2009 at 12:14pm
Are you using std::cin? That cuts off the word after it gets a whitespace.
Using getline(std::cin, myVariable) should work.
Oct 26, 2009 at 10:40pm
Thanks for replying bluezor.

I'm not using std::cin.
Could you give me some example code on how to use this getline(std::cin, myVariable)?
Sorry. I'm completely new to programming.
Last edited on Oct 26, 2009 at 10:41pm
Oct 27, 2009 at 9:47am
You really don't need to use a string for what you're trying to do, unless you wanna do something really long.

Try:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
	char items[20];

	cin.getline(items, 20);

	cout << items;
}


That should work for what you're trying to do.
Oct 27, 2009 at 10:43am
Not 100% sure if this works on a string array, but try this -
getline(std::cin, items[0]);
Oct 27, 2009 at 5:04pm
Can I have it so that a "cout<<items[0];" line will accept the words BLUE CHEESE?


EDIT: misunderstanding about what items was. However it doesn't change that cout is not the problem. The problem was filling the strings. Spaces in the string will not affect cout.

cout isn't the problem. You are attempting to send 1 of the stringsto the output stream because you are using the operator[] to access the first element of the array.

Take bluezor's first piece of advice and stick with std::string. Using a char buffer can cause array overflow which is undefined behavior. It is much safer to use std::string with getline. However, if you really want to there is a version of getline that takes a char*.
Last edited on Oct 27, 2009 at 9:29pm
Oct 27, 2009 at 5:23pm
Hrm, I think he might be trying to make an array on 20 std::strings rather than a string of 20 characters.
Topic archived. No new replies allowed.