#include <iostream>
#include <fstream>
#include <string>
usingnamespace 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';