Is there any way to read a formatted string like this, for example :48754+7812=Abcs
.
Let's say I have three stringz X,Y and Z, and I want
X = 48754
Y = 7812
Z = Abcs
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.
Is it possible to give C++ a parameter like this
":#####..+####..=SSS.."
so it knows directly what's going on?
The function scanf() is used for formatted input from standard input and provides many of the conversion facilities of the function printf().
The C language comes with standard functions printf() and scanf() so that a programmer can perform formatted output and input in a program. The formatted functions basically present or accept the available data (input) in a specific format.
C provides standard functions scanf() and printf(), to perform formatted inputs and outputs. These functions accept a format specification string and a variable list as the parameters.
#include <iostream>
#include <sstream>
int main(int argc, char **argv) {
std::string str = ":12341+414112=absca";
std::stringstream ss(str);
int v1, v2;
char col, op, eq;
std::string var;
ss >> col >> v1 >> op >> v2 >> eq >> var;
std::cout << v1 << " " << v2 << " " << var << std::endl;
return 0;
}
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;
}
Or, using 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 << "\n";
std::cout << "Y=" << Y << "\n";
std::cout << "Z=" << Z << "\n";
}
return 0;
}
However, the limitiation here is that the maximum length of the string (Z
) must be decided before parsing the input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With