Email: bknpk@hotmail.com Phone: +972-54-7649119


V

 

Simple c++ exercise to split a string into fields.
The program scans a text file. If a line contains field 1 = filed 2, the fields are extracted into to two fields. From each field spaces are removed (rm_spaces).
More c++ examples at: c++ page

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5. void rm_spaces(string& st) {
  6.   size_t next;
  7.   next = st.find_first_of( " ", 0 );
  8.   while(next != string::npos) {
  9.     st=st.substr(0, next) + st.substr(next+1);
  10.     next = st.find_first_of( " ", 0 );
  11.   }
  12. }



  13. int main ()
  14. {
  15.   string st, sr, su;
  16.   fstream infile;
  17.   size_t next;
  18.   infile.open ("Diversity_20_Receiver_Init_Val", ios::in);
  19.   while(getline(infile,st))
  20.   {
  21.     //split based on if if found
  22.     getline(infile,st);
  23.     next = st.find_first_of( "=", 0 );
  24.     if(next != string::npos) {
  25.       sr=st.substr(0, next++);
  26.       rm_spaces(sr);
  27.       su=st.substr(next);
  28.       rm_spaces(su);
  29.       cout << st << endl;
  30.       cout << sr << endl;
  31.       cout << su << endl;
  32.       cout << next << endl;
  33.     }
  34.   }
  35.   infile.close();
  36. }
  ...


Search This Site


Feedback This Site




new pages on this site