Problem with reading from FILE*

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

int main(){

	vector<string> strs;
	FILE* f = _popen("tasklist", "r");
	char str[90];

	while (fgets(str, 90, f)) {
		strs.push_back(str);
	}

	

	for (string& x : strs) {
		
		cout << x;

		x.pop_back();
		cout << x<<endl;

		x.pop_back();                       //error
		cout << x<<endl<<endl;
	}
	
	_pclose(f);

	cin.sync();
	cin.ignore();
	return 0;
}





The pop_back() call from line 21 causes unhandled exception std::out_of_range. Doing x.erase(x.end() - 2, x.end()); instead of the two pop_backs causes the same thing. This means there is a problem with the forelast character in x. What is wrong ?
Last edited on
I'm trying to delete last two characters in every string from strs container. Ignore the couts in my loop.
Last edited on
You should check if the length of the string is >= 2 before you remove two characters.
What a shame, that was the problem indeed. It seems the first string returned from "tasklist" command is only containing a newline character. I had no idea.
Topic archived. No new replies allowed.