/* File: input8.cpp Testing file I/O using >> with strings. */ #include #include #include #include #include // so you can use istringstream using namespace std ; int main() { string oneLine ; string str1, str2, str3, str4, str5, str6, str7, str8, str9 ; string str10, str11 ; long int population ; float litRate ; ifstream ifile("2013WorldBankEducationCensusData.txt") ; getline(ifile, oneLine) ; while(true) { getline(ifile, oneLine) ; // read entire line // cout << oneLine << endl ; // if ( ifile.eof() ) break ; if ( ifile.fail() ) break ; // works if last line does not have \n // Convert string to stringstream // new one each loop! // istringstream istrm(oneLine) ; istrm >> str1 ; // read from istrm istrm >> str2 ; istrm >> str3 ; istrm >> str4 ; istrm >> str5 ; istrm >> str6 ; istrm >> str7 ; istrm >> str8 ; istrm >> str9 ; istrm >> str10 ; // extra read attempts OK istrm >> str11 ; cout << "country = '" << str1 << "' " ; population = atol(str2.c_str()) ; cout << "population = " << population << " " ; if ( str3 == "N/A" ) { litRate = -1.0 ; } else { litRate = atof(str3.c_str()) ; } cout << "literacy rate = " << litRate << endl ; /* cout << "str2 = '" << str2 << "'\n" ; cout << "str3 = '" << str3 << "'\n" ; cout << "str4 = '" << str4 << "'\n" ; cout << "str5 = '" << str5 << "'\n" ; cout << "str6 = '" << str6 << "'\n" ; cout << "str7 = '" << str7 << "'\n" ; cout << "str8 = '" << str8 << "'\n" ; cout << "str9 = '" << str9 << "'\n" ; */ } ifile.close() ; }