Getline gets 2 words at a time while searching for ' '

Hello,
I've got problem with getline(), I'm trying to load all words to vector from a file.
1
2
3
4
5
6
7
8
9
   
 fstream plik;
    plik.open("plik.txt");
    string x;
    while(getline(plik,x,' '))
    {
        y.push_back(x);
    }
    plik.close();

y is a vector in class and this code is in one of its class methods.
The problem is the last word of the line is combined with the first of the next line and they have some kind of blank character between them.
I used my read method to get all elements and the letter of the "bugged" element. It also show the value of the char.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void read()
    {
    for(int i=0; i<y.size(); i++)
           {
            cout<< y[i] << " " ;
           }
    cout << endl;

    for (int i=0; i<y[4].length(); i++)
    {
        int z = 0;
        z=y[4].at(i);
        cout << y[4].at(i) <<" " << z<< endl;
    }
}
    

When I try to read the combined element this appears:
I don't know what wrong;
with that file;
cxzcxzczx.
w - 199
r - 114
o - 111
n - 110
g - 103
; - 59

 - 10
w - 119
i - 105
t - 116
h - 104

I have no idea how to fix that. Can anyone help me? I want to all the words to be unique elements of vector.
That 10 is end of line, \n.

By default, getline skips it, but you've told it not to. Your code should look like:
1
2
3
4
5
6
    fstream plik("plik.txt");
    string x;
    while (getline(plik, x))
    {
        y.push_back(x);
    }

And don't call open/close on file streams.
Last edited on
Thanks a lot, it works.

Well, I need to get the text in same shape as I loaded it, so how to get positions of the ends of lines?
Why shouldn't I call the open/close on file streams?
Last edited on
inf.txt:
w - 199
r - 114
o - 111
n - 110
g - 103
; - 59 //discard
//discard
- 10 //discard
w - 119
i - 105
t - 116
h - 104
r - 114 //discard


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
32
33
34
35
36
37
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // find()
#include <cctype> // isalpha()
using namespace std;

bool find_it(string s, vector<string> vect) {
	vector<string>::iterator iter;
	iter = find(vect.begin(), vect.end(), s);
	if(iter != vect.end())
		return false;
	else return true;	
}


int main () {
string s;
vector<string> vect;

ifstream in;
in.open("inf.txt");

while(!in.eof()) {
	getline(in, s);
	bool b= find_it(s, vect);
	if(isalpha(s[0]) && b)
		vect.push_back(s);	
}

for(auto x: vect) {
	cout << x << endl;
}

in.close();	
return 0;
}
Topic archived. No new replies allowed.