Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterator value to variable

Tags:

c++

iterator

I am using an iterator in a C++ code to retrieve records read using sqlite3 statements. I am able to display the contents pointed to by the iterator to screen using cout. How would i assign the value to a simple float or array variable.

typedef vector<vector<string> > Records;
vector< vector<string> >::iterator iter_ii;
vector<string>::iterator iter_jj;

Records records = select_stmt("SELECT density FROM Ftable where PROG=2.0");

  for(iter_ii=records.begin(); iter_ii!=records.end(); iter_ii++)
   {
      for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)
      {
         cout << *iter_jj << endl; //This works fine and data gets displayed!

         //How do i store the data pointed to by *iter_jj in a simple float variable or array?
      }
   }
like image 590
user2785789 Avatar asked Jun 30 '26 15:06

user2785789


1 Answers

C++ is type-safe, so you need to explicitly convert the string to the desired target type.

For float for example you could use atof:

float f = atof(iter_jj->c_str());

A more convenient alternative is Boost's lexical_cast, which works with the same syntax for all types that support extraction from an std::istream:

float f = boost::lexical_cast<float>(*iter_jj);

Note that both of these can fail in different ways if the contents of the string cannot be converted to a float in any meaningful way.

like image 117
ComicSansMS Avatar answered Jul 03 '26 04:07

ComicSansMS