STL List

user inputs a string
i want to load the string in to my nodes of my List


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <list>

using namespace std;

int main()
{
	string a;
	
	cout << "Enter 5 lines." << endl;
	
	list <string> myList(5);
	list<string>::iterator it = myList.begin();
	//input a atring and load it
	for(string it;it != myList.end();it++)
	{
		cin >> a;
		myList.insert(a);
	}
	
	return 0;
}
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
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <list>
#include <iterator>

using namespace std;

int main()
{
	string input;

	
	cout << "Enter 5 lines." << endl;
	
	list<string> myList(5);
	list<string>::iterator it = myList.begin();
	
	while (cin >> input && it != myList.end())
    {
		myList.push_back(input);
		if(input.size() > 40)
		{
			input.substr(0,40);
		}
		
		it++;
	}

	return 0;
}


but now my list is size 5 but i can input more than 5
I am not sure if I understand correctly. If you need to store some strings in a list you could do it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <list>

using namespace std;

int main()
{
  const int NUM_LINES = 5;
  string line;
  list <string> myList;
  cout << "Enter 5 lines." << endl;
  for (int i = 0; i < NUM_LINES; i++)
  {
    cout << "Enter line " << i + 1 << " ";
    getline(cin, line);
    myList.push_back(line);
  }
  // display the lines
  for (const string& line : myList)
    cout << line << "\n";

  return 0;
}


EDIT reason - see gunnerfunner's post below
Last edited on
Thomas - you're pushing back a list that has already allocated some memory
@gunnerfunner,
thanks, you were right. Corrected now
Topic archived. No new replies allowed.