reading with cin strings into a char sequence

Before everything, hello everyone! i have been visiting this site since i am starting to learn c++. Everytime i dont know how to do something, your site has the answer!

I'd like to simulate a string in c++ with a char sequence, but when i want to insert via cin some string into the char sequence i got a problem with sentences that contains a space: the char sequence will only store the first word in the sentence inserted by the user.

There is an example:

int main(int argc, char *argv[])
1
2
3
4
5
6
7
8
9
10
{
	char str[256];
	cout << "insert sentence\n";
	cin >> str;
	cout << "your sentence: \n";
	for(int i=0; str[i]; i++) cout << str[i];
	cout << "\n";
	system("PAUSE");
	return EXIT_SUCCESS;
}


if you test this code with "hello i am a sentence" it will return only "hello".

How do i can make my program to read the " " character into the str variable? Any help is welcome!
Last edited on
wow! getline works epicly... thanks iHutch!

and thanks for the suggestion of using string library... it worked okay with my char sequence. The code worked like this:

1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char *argv[])
{
	char str[256];
	cout << "insert sentence\n";
	cin.getline(str,256);
	cout << "your sentence: \n";
	for(int i=0; str[i]; i++) cout << str[i];
	cout << "\n";
	system("PAUSE");
	return EXIT_SUCCESS;
}



thanks a lot!
Do I see the use of system() in this program???????

How DARE you use batch when C++ has a function that will work just as well?

Use cin.get() and remove stdlib.h from your header.
Topic archived. No new replies allowed.