有没有办法读取这样的格式化字符串,例如: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模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)
使用字符串类输入空格时出现 cin 问题Issue with cin when spaces are inputted, using string class(使用字符串类输入空格时出现 cin 问题)