1

Given a text file just like (file.txt):

1234567A (THIS IS TAB) Peter, ABC (THIS IS TAB) 23523456
1345678A (THIS IS TAB) Michael CDE (THIS IS TAB) 23246756
1299283A (THIS IS TAB) Andy (THIS IS TAB) 98458388

ifstream inFile; string s; string id; string name; int phoneNo; inFile.open("file.txt"); while (!inFile.eof()) { getline(inFile, s, '\t'); } 

How can I extract a string of a line into different fields? For example, when I print s, it gives 1234567A. I have tried some techniques found in Stackoverflow, however, I cannot achieve the goal.

Thanks.


One more thing I want to ask is if the third field (i.e. phoneNo) consists of 1-3 elements,

1234567A (THIS IS TAB) Peter, ABC (THIS IS TAB) 23523456 (THIS IS TAB) 12312312
1345678A (THIS IS TAB) Michael CDE (THIS IS TAB) 23246756
1299283A (THIS IS TAB) Andy (THIS IS TAB) 98458388 (THIS IS TAB) 123123123 (THIS IS TAB) 123123123

How can I distinguish the number of phoneNo?

1 Answer 1

3
#include <iostream> #include <fstream> #include <sstream> #include <string> //... std::ifstream inFile( "file.txt" ); std::string record; while ( std::getline( inFile, record ) ) { std::istringstream is( record ); std::string id; std::string name; int phoneNo = 0; is >> id >> name >> phoneNo; } 

or

#include <iostream> #include <fstream> #include <sstream> #include <string> //... std::ifstream inFile( "file.txt" ); std::string record; while ( std::getline( inFile, record ) ) { if ( record.find_first_not_of( " \t" ) == std::string::npos ) continue; std::istringstream is( record ); std::string id; std::string name; int phoneNo = 0; is >> id >> name >> phoneNo; } 

If for example field name consists from several words when instead of the operator >> you should use again function std::getline For example

#include <iostream> #include <fstream> #include <sstream> #include <string> //... std::ifstream inFile( "file.txt" ); std::string record; while ( std::getline( inFile, record ) ) { if ( record.find_first_not_of( " \t" ) == std::string::npos ) continue; std::istringstream is( record ); std::string id; std::string name; int phoneNo = 0; std::getline( is, id, '\t' ); std::getline( is, name, '\t' ); is >> phoneNo; } 

If the number of phones cna be variable you should either use std::vector<unsigned int> or std::vector<std::string> and change the last statement of the function I showed the following way

 while ( is >> phoneNo ) v.push_back( phoneNo ); 

where v can be defined for example as std::vector<unsigned int>

Sign up to request clarification or add additional context in comments.

2 Comments

if the cotent of name is "Peter ABC" it cannot cout the correct name... how can solve it?
with reference to the bold problem, how can i solve it? i tested it using if phoneNo2==" ").... but it doesn't work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.