Best way to get ints from a string with whitespace

2019-01-17 12:14发布

I know this is simple, I just can't recall the best way to do this. I have an input like " 5 15 " that defines the x and y of a 2D vector array. I simply need those two numbers into int col and int row.

What's the best way to do this? I was attemping stringstreams, but can't figure out the correct code.

Thanks for any help!

5条回答
ら.Afraid
2楼-- · 2019-01-17 12:37

Here's the stringstream way:

int row, col;
istringstream sstr(" 5 15 ");
if (sstr >> row >> col)
   // use your valid input
查看更多
不美不萌又怎样
3楼-- · 2019-01-17 12:39

I personally prefer the C way, which is to use sscanf():

const char* str = " 5 15 ";
int col, row;
sscanf(str, "%d %d", &col, &row); // (should return 2, as two ints were read)
查看更多
老娘就宠你
4楼-- · 2019-01-17 12:43

Assuming you've already validated that the input is really in that format, then

sscanf(str, "%d %d", &col, &row);
查看更多
欢心
5楼-- · 2019-01-17 12:56

The C++ String Toolkit Library (StrTk) has the following solution to your problem:

int main()
{
   std::string input("5 15");
   int col = 0;
   int row = 0;
   if (strtk::parse(input," ",col,row))
      std::cout << col << "," << row << std::endl;
   else
      std::cout << "parse error." << std::endl;
   return 0; 
}

More examples can be found Here

Note: This method is roughly 2-4 times faster than the standard library routines and rougly 120+ times faster than STL based implementations (stringstream, Boost lexical_cast etc) for string to integer conversion - depending on compiler used of course.

查看更多
爷的心禁止访问
6楼-- · 2019-01-17 12:58

You can do it using a stringstream:

std::string s = " 5 15 ";
std::stringstream ss(s);

int row, column;
ss >> row >> column;

if (!ss)
{
    // Do error handling because the extraction failed
}
查看更多
登录 后发表回答