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
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- void rm_spaces(string& st) {
- size_t next;
- next = st.find_first_of( " ", 0 );
- while(next != string::npos) {
- st=st.substr(0, next) + st.substr(next+1);
- next = st.find_first_of( " ", 0 );
- }
- }
- int main ()
- {
- string st, sr, su;
- fstream infile;
- size_t next;
- infile.open ("Diversity_20_Receiver_Init_Val", ios::in);
- while(getline(infile,st))
- {
- //split based on if if found
- getline(infile,st);
- next = st.find_first_of( "=", 0 );
- if(next != string::npos) {
- sr=st.substr(0, next++);
- rm_spaces(sr);
- su=st.substr(next);
- rm_spaces(su);
- cout << st << endl;
- cout << sr << endl;
- cout << su << endl;
- cout << next << endl;
- }
- }
- infile.close();
- }
|