Converting string to integer (C++) | Sololearn: Learn to code for FREE!

0

Converting string to integer (C++)

I have one homework related to convert string to integer. Can anybody give me some example?

10/29/2019 9:24:05 AM

Aaron Pong

7 Answers

New Answer

+1

Make a program that reads every character of the string and then adds every read character in a certain way

+3

#include <iostream> #include <string> using namespace std; int main() { string str = "123"; //stoi is string to integer int d = stoi(str); cout << d * 2; return 0; } OUTPUT: 246

+2

Aaron Jason You should know loops for iterating over the string and should be aware of Ascii table (for knowing what you need to do to convert char '1' to integer 1). You may not actually need ascii table here but every programmer should be familiar with it. Hint - To convert char '1' to integer 1 you need to do char char1 = '1'; int int1 = char1 - 48;

+1

C++ has inbuilt function for converting string into integer ( stoi function) http://www.cplusplus.com/reference/string/stoi/

+1

Vijay Meena Yes C++ has built in functions to do that but does not help in learning how it is done actually.

+1

Alvaro 1234 Thanks 🙏 That's a very common trick. Instead of 48 you can also use '0' since char '0' has value 48 in ascii table.

0

~ swim ~ That's so cool, I knew that trick worked for transforming to upper or lower case, I didn't know you could also use it for numbers