c++ - How to read integers from a text file containing symbols, numbers and maybe alphabets? -


how read integers following text file containing symbols, numbers , maybe alphabets?

i have following text file

@ 100:20 ; 20:40 ; #  @ 50:30 ; #  @ 10:21:37 ; 51:23 ; 22:44 ; # 

i have tried following codes :

int main() {     std::ifstream myfile("10.txt", std::ios_base::in);      int a;     while (myfile >> a)     {        std::cout<< a;     }      return 0; } 

and

void main() {    std::ifstream myfile("10.txt", std::ios_base::in);    std::string line;     while (std::getline(infile, line))    {        std::istringstream iss(line);        int n;        while (iss >> n)        {          std::cout << n ;        }      } } 

all garbage value of int variable (or initial value if initialize )

how solve this?

you can try splitting each line separate tokens delimited colon character:

int main() {     std::ifstream myfile("10.txt", std::ios_base::in);     std::string line;      while (std::getline(myfile, line))     {         std::istringstream iss(line);         std::string token;         while (std::getline(iss, token, ':'))         {             std::istringstream tss(token);             int n;             while (tss >> n)             {                 std::cout << n << std::endl;             }         }     }      return 0; } 

this should print:

100 20 20 40 50 30 10 21 37 51 23 22 44 

as per comment, recommend more robust parsing algorithm respects unique structure of files.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -