0

I have the following function

template<class T> T stringTo(const std::string& s)
{
 std::istringstream iss(s);
  T x;
  iss>>x;
  return x;
};

and when I apply it as follows:

session ft = stringTo<session>("F");

where session is:

enum session {F, S, T};

I get a Segmentation fault.

can you help me figure out where my error lies...

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
itcplpl
  • 780
  • 4
  • 18
  • 29
  • 2
    What do you expect the result of casting the integer 70 to an enum with values 0, 1, and 2 will be? – Bill Nov 08 '11 at 01:44
  • 2
    To elaborate on @Bill's comment, `'F'` and `F` are _not_ the same thing, and IOStreams does not magically form a link between the two. You'll need a switch-case block or something like that for a specialisation of `stringTo`. – Lightness Races in Orbit Nov 08 '11 at 01:46
  • (In addition, this is not your real testcase, because your real testcase uses `"F"`, not `'F'`. Please don't post fake testcases.) – Lightness Races in Orbit Nov 08 '11 at 01:47
  • 1
    yes it does compile....granted the single quote was a typo... – itcplpl Nov 08 '11 at 01:52
  • any possibility of a constructive response now... – itcplpl Nov 08 '11 at 01:53
  • @itcplpl: I already gave you one. Both an explanation and a solution may be found in my comment. I didn't flesh it out into a full answer, but still... – Lightness Races in Orbit Nov 08 '11 at 02:01
  • @itcplpl: In future, please only post code when it's a testcase that you have already been debugging with, and which you _know_ exhibits only the problem that you are asking about. Otherwise how are we to know which problems you know about and which you don't? Typos are completely avoidable, and waste our time/brainpower! – Lightness Races in Orbit Nov 08 '11 at 02:02

1 Answers1

1

Could the problem be that you are using 'F' instead of "F"?

It seems like your stringTo function wants a string and you are sending in a char.

Btw, I don't think your approach is valid. You probably need to setup a map that takes you from string to enum or vice versa.

Maybe, this might give you an option.

Community
  • 1
  • 1
Nabheet
  • 1,285
  • 1
  • 12
  • 22
  • That's _a_ problem, but not the one the OP is asking about. – Lightness Races in Orbit Nov 08 '11 at 01:48
  • @TomalakGeret'kal: OP asked about a segfault, it looks like passing a char instead of a pointer would give a segfault... Obviously the OP's code is wrong and won't do what he wants, but as to his question, I think this _is_ the answer. – Mooing Duck Nov 08 '11 at 01:53
  • @Mooing: Um, won't it simply fail to compile? (I'm not aware of a non-`explicit` `std::string` constructor taking only a `char`.) Quite different. – Lightness Races in Orbit Nov 08 '11 at 01:57