Oh, I'd actually recommend Boost Spirit (Qi), see below later for an example
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
ifstream myfile ("example.txt");
std::string line;
while ( std::getline(myfile, line) )
{
std::istringstream iss(line.substr(0,3));
int i;
if (!(iss >> i))
{
i = -1;
// TODO handle error
}
std::string tail = line.size()<4? "" : line.substr(4);
std::cout << "int: " << i << ", tail: " << tail << std::endl;
}
return 0;
}
Just for fun, here is a more flexible Boost based solution:
#include <boost/spirit/include/qi.hpp>
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
ifstream myfile ("example.txt");
std::string line;
while ( std::getline(myfile, line) )
{
using namespace boost::spirit::qi;
std::string::iterator b(line.begin()), e(line.end());
int i = -1; std::string tail;
if (phrase_parse(b, e, int_ >> *char_, space, i, tail))
std::cout << "int: " << i << ", tail: " << tail << std::endl;
// else // TODO handle error
}
return 0;
}
If you really must have the first three characters as integers, i'd stick with the pure STL solution for now