I have the line "abc = 14.22 xyz = 33, tdc = 48" in the file. How can I split it into strings and their corresponding values ​​in C ++?

I have a line "abc=14,22 xyz=33, tdc=48"in a file. How can I split it into strings and their corresponding values ​​in C ++? as -

abc = 14,22
xyz = 33
tdc = 48
+3
source share
2 answers
char * astr = "abc=14,22 xyz=33, tdc=48";

int abc1, abc2,xyz,tdc;

sscanf(astr,"abc=%d,%d xyz=%d, tdc=%d",&abc1,&abc2,&xyz,&tdc);
+5
source

If you need to read a line from a file, you can use std::ifstream:

std::ifstream fs( "some_file.txt" );
std::string input_string;
while ( getline(fs, input_string) ) {
  // parse a string
}

Then, just for fun, the regex version, as you could parse the input string:

#include <iostream>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
  const std::string input_string = "abc=14,22 xyz=33, tdc=48";

  // this is a regular expression that will parse the input_string
  boost::regex expr( "^abc=(\\d+,\\d+) xyz=(\\d+), tdc=(\\d+)$" );

  boost::match_results<std::string::const_iterator> what;
  if ( regex_search( input_string, what, expr )) {
    // we'll get here only if Regex will find all required parts

    // abc = ?
    std::string abc_str( what[1].first, what[1].second );
    // convert abc to a float variable
    std::replace( abc_str.begin(), abc_str.end(), ',', '.' );
    float abc = boost::lexical_cast<float>( abc_str );

    // xyz = ?
    std::string xyz_str( what[2].first, what[2].second );
    // convert xyz to an int variable
    int xyz = boost::lexical_cast<int>( xyz_str );

    // tdc = ?
    std::string tdc_str( what[3].first, what[3].second );
    // convert tdc to an int variable
    int tdc = boost::lexical_cast<int>( tdc_str );

    // check result
    std::cout << abc << std::endl;
    std::cout << xyz << std::endl;
    std::cout << tdc << std::endl;
  }
  return 0;
}

In your particular question, using Regex is redundant, but in more complex cases it can be useful.

+2
source

Source: https://habr.com/ru/post/1757279/


All Articles