14.5k views
3 votes
Write a function that converts a string into an int. Assume the int is between 10 and 99. Do not use the atoi() or the stoi() function.

1 Answer

6 votes

Answer:

Written in C++

#include <iostream>

#include <sstream>

using namespace std;

int main() {

string num;

cout<<"Enter a number: ";

cin>>num;

stringstream sstream(num);

int convertnum = 0;

sstream >> convertnum;

cout << "Output: " << convertnum;

}

Step-by-step explanation:

Without using atoi() or stoi(), we can make use of a string stream and this is explained as follows:

This line declares a string variable num

string num;

This line prompts user for input

cout<<"Enter a number: ";

This line gets user input

cin>>num;

This line declares a string stream variable, sstream

stringstream sstream(num);

This line declares and initializes the output variable, convertnum to 0

int convertnum = 0;

The stream is passed into the output variable, convertnum

sstream >> convertnum;

This line displays the output

cout << "Output: " << convertnum;

Note that: if user enters a non integer character such as (alphabet, etc), only the integer part will be convert.

For instance,

40a will be outputted as 40

User Steve Lewis
by
9.5k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.