please help :)

hello
i want to declare string in vector,
for example : i want to take from user words and cout it
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

#include <iostream>

#include <string>
#include <vector>


using namespace std;
int main()
{
	 string v;
	 getline(cin,v);
	vector < string > str ( v.size() );

	for(int i=0;i<str.size()-1;i++)
	{
		cout<<str[i];
	}


	


}


The constructor you are calling for vector will fill the vector with v.size() copies of default constructed strings. So your vector will hold v.size() strings with nothing in them.
You just want to push your string back using str.push_back(v).
Or if you want to use the constructor call:
vector<string> str(1,v).
This will fill the vector with 1 copies of v.
Each item in a vector holds the whole data structure or class. You don't need to reserve a spot for each character.
About Vectors :http://www.cplusplus.com/reference/stl/vector/

I don't think you add the string to the vector.

Try removing the ( v.size() ) from line 13, I think you've made a vector the size of the length of string v.

str.push_back(v); at line 14 will actually ad the string to the vector, otherwise your vector is empty.

You also need to pause the program after your for loop and main() needs to return a value
thank you :)
You also need to pause the program after your for loop and main() needs to return a value

It's not always you want to pause a program. main() will return 0 if there is no return statement.
Last edited on
I suppose not, I guess my first thought is this is being tested in an IDE.
Code::Blocks has a "console runner" that pauses and tells you the return value and execution time. Nice for testing console apps without having to add a pause.
Topic archived. No new replies allowed.