Help Please

Someone please explain what I have to do here. It's part of a test review and this is something the professor never went over. I'm having a lot of trouble trying to figure out how I am suppose to do this

Write a function int str_to_int(const string& s) which assumes that the string s represents an integer and returns the value of this integer. For example, if the s=”-257” then the function applied to this string returns the value 257.
Start by breaking it down into steps.

Write a function int str_to_int(const string& s)

Do you know what functions are? Does int str_to_int(const string& s) mean anything to you?
Last edited on
One way to do it is to iterate through the whole string and convert the digit to a number for example '1' - '0' => 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int str_to_int(const string& s)
{
  int sum = 0;

  for (char ch: s)
  {
    if (ch >= '0' && ch <= '9') // only digits
    {
      sum *= 10;
      sum += ch - '0';
    }
  }
  return sum;
}


@Moschops the professor never taught it in class or given us examples to better understand. I'm really new to it so I can't say that it does.

@Thomas1965, Thank you! So if I'm understanding this correctly, this goes outside of the main function. Inside the main function (lets say string x) I prompt the user to input a number. After the user enters the number I would cout << str_to_int(x).


Also if I wanted to have it accept doubles I know that it is int str_to_double(const string& s), would I follow the same outline for the code?
Last edited on
Unfortunately converting to double is more complicated because of the decimal point.
Have a look here:
http://stackoverflow.com/questions/4392665/converting-string-to-float-without-atof-in-c
or google for "char* to double c++ without library functions"
Topic archived. No new replies allowed.