Vector.Size() error!

I am using getline()to get bunch of strings and push them into the vector. I don't why but when i type words.size() it always says 2 but there are more than two elements in the vector.

1
2
3
4
5
6
7
8
  string user_input;
  vector<string>words;

	while(getline(cin,user_input)){
		words.push_back(user_input);
		if(user_input=="")break;
	}
	cout<<words.size();


I tried my best searching in google but no one has used vector.push_back() and getline function.
Last edited on
What input do you enter?
You need to check if the string is empty before you add it. Otherwise your count is too high.
I believe you should do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main(){
vector < string > words;
string userInput;

while (getline(cin, userInput)){
    if (userInput==""){
        break;
    }
    else{
        words.push_back(userInput);
    }
}
cout<<words.size();
}
I may be wrong, but Is it true that the element of this vector<string>user_input will always be equal to 1 because the getline() appends these elements into the strings so the vector always has just 1 big string?

My Goal: I want to be able to manipulate with lines of a paragraph and add endl; at the end of every line with a certain character restriction in every line.
Last edited on
element of this vector<string>user_Input

Seems to be slightly mixed up there.
The code has a vector called words and a string called userInput. It doesn't have anything called user_Input.

The elements of vector<string> words will each be a string.
getline() replaces the previous contents of the string.
push_back() adds a new element to the vector.

Let's look at an example. Here I'm using a stringsteam called input for convenience. You could replace input with cin at line 22.

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 <vector>
#include <string>
#include <sstream>

std::istringstream input(
    "The quick\n"
    "brown fox jumps\n"
    "over the\n"
    "\n"
    "lazy dog\n"
);


using namespace std;

int main()
{
    vector < string > words;
    string userInput;

    while ( getline(input, userInput) && userInput.size() )
    {
        words.push_back(userInput);
    }
    
    cout << "Size = " << words.size() << '\n';
    
    for (string & s : words)
        cout << s << '\n';
}


Output:
Size = 3
The quick
brown fox jumps
over the


Notice the while loop stopped accepting input when it found a line with a length of zero , that is the same as the string "".

Last edited on
@Chervil Thank you for explaining it. I get it now! I had the definition of getline() also mixed up.
Topic archived. No new replies allowed.