Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The easiest way to read formatted input in C++?

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?

like image 796
Loers Antario Avatar asked Jul 07 '12 11:07

Loers Antario


People also ask

What is used to read the formatted input from a string?

The function scanf() is used for formatted input from standard input and provides many of the conversion facilities of the function printf().

What is formatted input in C?

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.

What is formatted input output?

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.


2 Answers

#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;
}
like image 195
perreal Avatar answered Nov 02 '22 16:11

perreal


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.

like image 26
hmjd Avatar answered Nov 02 '22 15:11

hmjd