G
Gary Wessle
Hi
please look at the code below, the problem I have is that line 37 does
not print out into the file as expected. however if I move it to be
immediately after line 16 it prints fine into the file. apparently the
while block is doing something wicked and corrupting the stream.
how can I fix this?
thank you
1 #include <fstream>
2 #include <iostream>
3 #include <string>
4
5 /* Reads the value for the lookup string from file, and sets the value in m_pair_status
6 if the value does not exist, create it with a default.
7 */
8 double Grid::status( std::string lookup)
9 {
10 std::string f = "my_file_name";
11 std::fstream iofs( f.c_str(), std::ios::in|std::ios:
ut );
12 if (!iofs.is_open())
13 {
14 iofs.open( f.c_str(), stdios_base::in | ios_base:
ut |
15 ios_base::trunc );
16 }
17 std::string line, word;
18 double val;
19 bool found_it = false;
20 while( !found_it && getline( iofs, line ) )
21 {
22 std::stringstream ss( line );
23 ss >> word;
24 if( word == lookup )
25 {
26 found_it = true;
27 ss >> val;
28 m_pair_status[lookup] = val;
29 iofs.close();
30 return val;
31 }
32 }
33 // value does not exist, create it with a default
34 if( lookup == "reversals" )
35 {
36 val = 0;
37 iofs << "reversals" << " " << val << std::endl;
38 m_pair_status[lookup] = val;
39 } // add other lookups as needed
40 iofs.close();
41 return val;
42 }
please look at the code below, the problem I have is that line 37 does
not print out into the file as expected. however if I move it to be
immediately after line 16 it prints fine into the file. apparently the
while block is doing something wicked and corrupting the stream.
how can I fix this?
thank you
1 #include <fstream>
2 #include <iostream>
3 #include <string>
4
5 /* Reads the value for the lookup string from file, and sets the value in m_pair_status
6 if the value does not exist, create it with a default.
7 */
8 double Grid::status( std::string lookup)
9 {
10 std::string f = "my_file_name";
11 std::fstream iofs( f.c_str(), std::ios::in|std::ios:
12 if (!iofs.is_open())
13 {
14 iofs.open( f.c_str(), stdios_base::in | ios_base:
15 ios_base::trunc );
16 }
17 std::string line, word;
18 double val;
19 bool found_it = false;
20 while( !found_it && getline( iofs, line ) )
21 {
22 std::stringstream ss( line );
23 ss >> word;
24 if( word == lookup )
25 {
26 found_it = true;
27 ss >> val;
28 m_pair_status[lookup] = val;
29 iofs.close();
30 return val;
31 }
32 }
33 // value does not exist, create it with a default
34 if( lookup == "reversals" )
35 {
36 val = 0;
37 iofs << "reversals" << " " << val << std::endl;
38 m_pair_status[lookup] = val;
39 } // add other lookups as needed
40 iofs.close();
41 return val;
42 }