Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. In ANSII standard C++, there is no library function to convert an integer to

ID: 3547037 • Letter: 1

Question

 1. In ANSII standard C++, there is no library function to convert an  integer to a string. Your program should develop such a  function. In other words complete the following program using your  itos function. (Use of other C functions is prohibitted)  // this program will read in an integer and convert it to a string  #include <iostream> #include <cstdlib> #include <string>  using namespace std;  string itos(int n) { }   int main(int argc, char* argv[]){         int n = atoi(argv[1]);         cout << "file "+ itos(n)+ " .txt" << endl;         return 0; }

Explanation / Answer

string itos(int n) {
    string ss="";   //create empty string
    bool negative = false;    //flag for negative number
    if( n == 0 || n == -0){
         return "0";
    }
    //check for negativivity
    else if(n < 0){
    negative = true;
    n = n * -1; //changes back to positive
    }
    while(n)
    {
        int x=n%10;
        n/=10;
        char i='0';
        i=i+x;
        ss=i+ss;      //append new character at the front of the string!
    }
    if(negative){
        return "-" + ss;
    }
    return ss;
}