Problem with creating substring for last word

I'm having trouble figuring out how to find the last string in the file. I know my problem, but can't think of a way around 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
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){

	ifstream file;
	file.open("t.txt");
	if(file.is_open()){
		string fileString;
		while(getline(file, fileString)){
                        // If the line isn't blank
			if(fileString != ""){
                                // Does not read the first empty space
				if(fileString.substr(0, 1) == " "){
					fileString = fileString.substr(fileString.find(" ") + 1);
					cout << fileString << endl;
				}
				while(fileString != fileString.substr(0, fileString.find(" "))){
					string subString;
					subString = fileString.substr(0, fileString.find(" "));
					cout <<  "substring: "<< subString << endl;
                                        // This is my problem, the last word wouldn't have a space so I won't create substring for the last word
					fileString = fileString.substr(fileString.find(" ")+1); 
					cout << "file string:" << fileString << endl;
				}
				cout << endl;
			}
		}

	}


	return 0;
}
I'm having trouble figuring out how to find the last string in the file.

The easiest way, but not necessarily the fastest, is to read the entire file one line at a time into a string using getline(). Then after you've read all the lines parse the last line using a stringstream using the extraction operator>>. By the way this assumes you meant the last word.

Something like:

1
2
3
4
5
6
7
8
while(getline(input_file, your_string){ /* blank body */ }

stringstream sin(your_string);

while(sin >> your_string) { /* Blank body */}

cout << "The last string in the file is: " << your_string << '\n';
Last edited on
Topic archived. No new replies allowed.