0

I'm reading in a text file for a simulated compiler, and I'm trying to tokenize all the literals. When I realize it's a number value, I'm trying to store the number. However, since the entire line I'm reading from is a string, I only get the ASCII value for the number (i.e. 0 becomes 48), when I really need the value 0. Is there any way to obtain the literal value from the string/char I'm looking at?

example:

std::string IR = "set 0, read" int currentIRIndex = 4 // (looking at the 0 char) 

IR[currentIRIndex] is 0 if I call it from the << operator, and 48 (the ASCII value of 0) if I assign it to an integer.

4
  • 1
    Are you looking to convert one character at a time, or parse as many digits as you can find? Commented Apr 28, 2014 at 22:10
  • 2
    Though there are many (better) ways to convert a string to a number, I'm surprised you didn't at least consider cout << IR[currentIRIndex] -48 << "\n"; Commented Apr 28, 2014 at 22:11
  • I'm only worried about the current number I'm looking at. @DavidO Oh my gosh....what an easy solution. Talk about functional fixedness..... >_< Commented Apr 28, 2014 at 22:13
  • We all have those moments, I suppose. ;) Commented Apr 28, 2014 at 22:16

1 Answer 1

4
int v = IR[currentIRIndex] - '0'; 

this will give you the literal value

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

3 Comments

This didn't seem to work a few minutes ago, but now seems to work. Thanks again.
@LeoVannini: Note that this does not always work for the alphabet, but always works for the ten latin numeric digits.
this work in your use case with 1 char as a number, if you work with number > 9 this will not and you'll have to use solution to transform a string in int like atoi or boost lexical_cast or direclty with the stream

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.