0

I have the following template function:

  template <typename N>
  inline N findInText(std::string line, std::string keyword)
  {
    keyword += " ";
    int a_pos = line.find(keyword);
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(a_pos,line.length());
      N x;
      std::istringstream (actual) >> x;
      return x;
    }
    else return -1; // Note numbers read from line must be always < 1 and > 0
  }

It seems like the line:

 std::istringstream (actual) >> x;

Doesn't work. However the same function not templated:

    int a_pos = line.find("alpha ");
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(a_pos,line.length());
      int x;
      std::istringstream (actual) >> x;
      int alpha = x;
    }

Works just fine. Is it an issue with std::istringstream and templates ???

I am looking for a way to read configuration files and load parameters which can be int or real.

EDIT solution:

template <typename N>
  inline N findInText(std::string line, std::string keyword)
  {
    keyword += " ";
    int a_pos = line.find(keyword);
    int len = keyword.length();
    if (a_pos != std::string::npos)
    {
      std::string actual = line.substr(len,line.length());
      N x;
      std::istringstream (actual) >> x ;
      return x;
    }
    else return -1;
  }
2
  • How are you calling the function? What is N? Do you get a compilation error? Commented Jul 29, 2011 at 21:59
  • no compilation errors. I call the function as this: alpha = var::findInText<float>(line,"alpha"); Commented Jul 29, 2011 at 22:14

1 Answer 1

1

It doesn't work because the string you're reading in can't be converted to a number, so you're returning uninitialized garbage. That's happening because you're reading in the wrong string -- if line is foo bar 345 and keyword is bar, then actual gets set to bar 345, which doesn't convert to an integer. You instead want to convert 345.

You should rewrite your code like this:

    std::string actual = line.substr(a_pos + keyword.length());
    N x;
    if (std::istringstream (actual) >> x)
        return x;
    else
        return -1;

That way, you convert the proper substring, and you also properly handle the case when that can't be converted to an integer.

Sign up to request clarification or add additional context in comments.

2 Comments

Line contains three things a keyword a space and a number, and I'm only interested in the number.
Actually i needed: int len = keyword.length(); std::string actual = line.substr(len,line.length()); But thank you for pointing this out !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.