哦,其实我建议升压灵(齐),见下文稍后再例如
#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;
}
只是为了好玩,这里是一个更灵活的升压基础的解决方案:
#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;
}
如果你真的必须有前三个字符作为整数,我会坚持现在的纯STL解决方案
什么样的文字?而且该代码不会像你所问的那样做,而且在任何情况下都是错误的。 – 2011-05-16 10:57:34