tags:

views:

84

answers:

2

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

abc = 14,22
xyz = 33
tdc = 48
+5  A: 
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);
matt
I think that `abc` should be double and `%f`. And you should add a warning that this is not type safe. But it works perfectly
Gaim
i bet `abc` is an array. maybe you could fix that?
st0le
The 14,22 might be decimal 14.22 in European format. But it can be fixed later with `(abc1 + (abc2/100))` if that's the case.
Amardeep
+2  A: 

If you need to read a string from a file you could 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, a version with regular expressions how you could parse an 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 concrete question using Regex is overkill, but in more complex cases it could be useful.

Kirill V. Lyadvinsky
I knew that was coming :D
matt
@matt u win in space complexity :D
Kedar