0

Let's say that I have a string variable called "numbers" that is defined as "12345" in string:

string numbers = "12345";

If that is the case, how do I convert that variable so that I can store those as integers instead? Now I know that there are multiple ways to do it using the string library like stoi, atoi, stringstream, and etc... but the trick here is to make it possible WITHOUT using any of those. I personally do not understand this assignment when there are MUCH efficient ways to do it but that's just my opinion.

I was thinking if I would make a function where it stores individual numbers as array of chars using loops and somehow stick those together as an int. Am I going into the right track?

Thank you

EDIT: I am talking about c++

1
  • @KenY-N I understand, but are there any ways to replicate that in c++? Commented Jan 11, 2017 at 5:20

3 Answers 3

2

You can convert every char that you read to it's equivalent int by using (ch - '0').

std::string str = "12345";
int number = 0;

for(auto ch : str)
{
    number = (number * 10) + (ch - '0');
}

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

1 Comment

Yes. It's unnecessary. only if str contain any other char('a', 'b') instead of numbers, it hold resulting int between 0 to 9. I'll edit.
0

Try this:

string numbers = "12345";
int result = 0;
for (int i = 0; i < numbers.size(); i++) {
  result += (numbers[i] - 48) * pow(10, (numbers.size() - i - 1));
}
cout << result << endl;

Key idea is that char '0' is 48 in ASCII
You may check whether numbers[i] is in range 48 to 57 to validate input.

2 Comments

awesome. Thank you!
Why not use '0' instead of 48 then? And size() is a string library function (well, method) which the OP suggests they may want to avoid.
0
#include <iostream>
using namespace std;

int main() {
    string numbers = "12345";
    int result = 0;
    for (int digit : numbers)
        result = digit - 48 + result * 10;
    cout << result << endl;
    return 0;
}

Output

12345

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.