c++ string how do i input with spaces

i want the user to input a string with or without spaces

this is my code what do i need?
1
2
3
4
5
6
7
8
9
10
11
12
13
void inputf(list<string> &L)
{
	string input;
	int lines;
	cout << "How many lines do you want to enter: ";
	cin >> lines;
	for(int ins = 0; ins < lines; ins++)
	{
		cout << "Enter a line: ";
		cin >> input;
 	  	L.push_back(input);
	}
}
replace cin >> lines;
with
getline(std::cin, lines);
i used getline

but "enter a line" prints twice

also the space doesnt connect

if i do something like
hi there

this is 2 lines
Last edited on
it still print twice

1
2
3
cin >> repeat;
cin.ignore();
}while(repeat >= 1 && repeat <= 5);
this chops off the first character


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void inputf(list<string> &L)
{
	char input[40];
	int lines;
	cout << "How many lines do you want to enter: ";
	cin >> lines;
	
	for(int ins = 0; ins < lines; ins++)
	{
		cout << "Enter a line: ";
		cin.ignore();
		cin.getline(input,40);
 	  	L.push_back(input);
	}
}
gunnerfunner wrote:
replace cin >> lines;
with
getline(std::cin, lines);

I think you mean to replace cin >> input with getline(cin, input).
Last edited on
yes, and I also notice the list is std::string but OP is reading into char[], so re-working that a bit as well:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void inputf(list<string> &L)
{
	std::string input{};
	size_t lines{};
	std::cout << "How many lines do you want to enter: ";
	std::cin >> lines;
	std::cin.ignore();

	for(size_t ins = 0; ins < lines; ++ins)
	{
		std::cout << "Enter a line: ";
		getline(std::cin, lines);
 	  	L.push_back(lines);
	}
}
gunnerfunner wrote:
I also notice the list is std::string but OP is reading into char[]

Why did the OP use std::string in the first code and char[] in the second?

This code should work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void inputf(std::list<std::string>& L)
{
	std::string input;
	std::string::size_type lines = 0;

	std::cout << "How many lines do you want to enter: ";
	std::cin >> lines;

	for(std::string::size_type ins = 0; ins < lines; ++ins)
	{
		std::cout << "Enter a line: ";
		std::getline(std::cin, input);
 	  	L.push_back(input);
	}
}


Also, container::size_type instead of size_t is preferred for maximum portability. And you should stay consistent; you didn't add the std namespace qualifier on line 1.

There is a mistake in your code. On lines 12 & 13 lines should be input.
Last edited on
yes, boost, you're right
Topic archived. No new replies allowed.