I'm using the following code to read .txt files and print to console:
Code:
#include <iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<tuple>
using namespace std;
int main (){
fstream File;
string name, address;
int age;
vector<tuple<string,string,int>>v;
File.open("F:\\test.txt");
if(File.is_open()){
string line;
while(getline (File, line)){
stringstream stream(line);
while(stream>>name>>address>>age){
v.emplace_back(name, address, age);
}
}
}
for(auto& itr : v){
cout<<"name: "<<get<0>(itr)<<", address: "<<get<1>(itr)<<", age: "<<get<2>(itr)<<"\n";
}
}
When my .txt file is:
Name Address Age
John London 45
Jane Cambridge 31
Output:
Code:
name: John, address: London, age: 45
name: Jane, address: Cambridge, age: 31
Note that the first line of the .txt file (Name Address Age) is not printed in this case but if I remove the first line and start the .txt file with actual names, addresses, ages then still the first entry is printed fine. Why this dichotomy?
And when my .txt file is:
Name Address Age
John Smith Abbey Road, London 45
Jane Doe Huntingdon Road, Cambridge 31
The output is essentially nothing:
Code:
Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.
I understand that having whitespaces within data-fields is breaking down sstringstream but how could I then best write the program so that it can read strings with whitespaces within them into a single string and then move on to the next variable which could be another string with whitespaces within (as in this example) or some other datatype? It seems that the stringstream ctor does not take a delimiter, otherwise I might have tried ...
Code:
stringstream stream(line, ';');
... with the semi-colon delimiting the datafields in the .txt file.
Thanks as ever.