我知道这很简单,我只是不记得最好的方式来做到这一点。 我有一个输入,如" 5 15 "
,它定义了2D向量数组的x和y。 我只需要这两个数字到int col
和int row
。从空字符串中获取int的最佳方法是什么?
这样做的最好方法是什么?我正在尝试stringstreams,但无法弄清楚正确的代码。
感谢您的帮助!
我知道这很简单,我只是不记得最好的方式来做到这一点。 我有一个输入,如" 5 15 "
,它定义了2D向量数组的x和y。 我只需要这两个数字到int col
和int row
。从空字符串中获取int的最佳方法是什么?
这样做的最好方法是什么?我正在尝试stringstreams,但无法弄清楚正确的代码。
感谢您的帮助!
您可以使用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
}
我个人比较喜欢的C方式,这是使用sscanf()
:
const char* str = " 5 15 ";
int col, row;
sscanf(str, "%d %d", &col, &row); // (should return 2, as two ints were read)
的C++ String Toolkit Library (StrTk)有以下问题的解决方案:
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;
}
更多的例子可以发现Here
注意:此方法比标准库例程快大约2-4倍,比基于STL的实现快120倍以上(stringstream,Boost lexical_cast等)用于字符串到整数的转换 - 当然取决于编译器。
流不属于来自STL的std库的那部分。 – sbi 2010-12-15 02:01:14
这里的stringstream
方式:
int row, col;
istringstream sstr(" 5 15 ");
if (sstr >> row >> col)
// use your valid input
假设你已经验证的输入是真的该格式,然后
sscanf(str, "%d %d", &col, &row);
@Downvoters:如果在这个答案中有技术错误,请让我知道;否则我不知道什么是错的。 – 2010-04-12 01:05:13
在这种特殊情况下,downvoters有问题,而不是您的代码。 – wilhelmtell 2010-04-12 01:12:21
@wilhelmtell:+1,我同意。 – 2010-04-12 01:13:37