Problem 2 Write a function that converts a string into an integer. For example,
ID: 3870128 • Letter: P
Question
Problem 2 Write a function that converts a string into an integer. For example, given the string “1234", the function should return the integer 1234. You should write your own code to do the conversion (you may NOT use atoi function or the stringstream class). Write a main method to ask the user to enter a string and then outputs the resulting integer. For testing purposes, all test cases will have two outputs: 1) the integer, 2) the integer added to 10 (this is to make sure you are doing the conversion) You may assume that the string is a valid integer Reminder: To convert a character to a number, add 0 to the character. For example, to convert the character '0' to the number 0 char c = ‘0'; int number = static cast(c)-static. Cast('0');Explanation / Answer
#include<iostream>
#include<cstring>
using namespace std;
int strToInt(string s){
int n=0;
//process string
for(int i=0;i<s.length();i++){
// cast each digit to int
int num = static_cast<int>(s[i]) - static_cast<int>('0');
// add each digit at the last
n = n*10 + num;
}
return n;
}
int main(){
string s;
//get user input string
cout << "Enter number:";
cin >> s;
int n = strToInt(s);
cout << n << endl;
return 0;
}
/*
sample output
Enter number: 1234
1234
*/
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.