問題描述
有沒有辦法讀取這樣的格式化字符串,例如:48754+7812=Abcs
.
Is there any way to read a formatted string like this, for example :48754+7812=Abcs
.
假設我有三個字符串 X、Y 和 Z,我想要
Let's say I have three stringz X,Y and Z, and I want
X = 48754
Y = 7812
Z = Abcs
兩個數字的大小和字符串的長度可能會有所不同,所以我不想使用 substring()
或類似的東西.
The size of the two numbers and the length of the string may vary, so I dont want to use substring()
or anything like that.
是否可以給C++這樣的參數
Is it possible to give C++ a parameter like this
":#####..+####..=SSS.."
所以它直接知道發生了什么?
so it knows directly what's going on?
推薦答案
一種可能性是 boost::split()
,它允許指定多個分隔符并且不需要輸入大小的先驗知識:
A possibility is boost::split()
, which allows the specification of multiple delimiters and does not require prior knowledge of the size of the input:
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
int main()
{
std::vector<std::string> tokens;
std::string s(":48754+7812=Abcs");
boost::split(tokens, s, boost::is_any_of(":+="));
// "48754" == tokens[0]
// "7812" == tokens[1]
// "Abcs" == tokens[2]
return 0;
}
或者,使用sscanf()
:
#include <iostream>
#include <cstdio>
int main()
{
const char* s = ":48754+7812=Abcs";
int X, Y;
char Z[100];
if (3 == std::sscanf(s, ":%d+%d=%99s", &X, &Y, Z))
{
std::cout << "X=" << X << "
";
std::cout << "Y=" << Y << "
";
std::cout << "Z=" << Z << "
";
}
return 0;
}
然而,這里的限制是字符串的最大長度 (Z
) 必須在解析輸入之前確定.
However, the limitiation here is that the maximum length of the string (Z
) must be decided before parsing the input.
這篇關于在 C++ 中讀取格式化輸入的最簡單方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!