jeudi 19 mars 2015

Integer to String: Without using stoi library


I found this question in the book where it asks us to transfer an Int to a string. Without using stoi library so for example if x = 10, s="10" the code should handle negative numbers.


I found this solution in the book. I typed it in my compiler however it is giving the string of the first number only


so if x= 45, it is giving "4"


I do not understand this line s = '0' + x%10; to be able to fix the code. why is he adding '0' to the string. What is the best solution.


here is the code: I added comments to the parts I understand



#include<iostream>
#include<string>
using namespace std;


void IntToString(int x);
int main()
{
int num;
cout << "Please enter a number" << endl;
cin >> num;

IntToString(num);
}

void IntToString(int x)
{
bool isNegative = false;
if(x < 0) //if its negative make boolean true
{
x = -x;
isNegative = true;
}
string s;
do
{
s = '0' + x%10; //modulus for getting the last number
x = x/10; //shorten the number
}while(x);
reverse(s.begin(), s.end()); //reverse the string since it starts from end

if(isNegative)
s = '-' + s;
cout << s << endl;
}



Aucun commentaire:

Enregistrer un commentaire