Squaring Array Numbers Question

I am new to programming and is stuck on a excersize from the book. Basically the user gets to input the number of digits they want to use in a number. They then enter a number. I save that number as a string and use number.length() to match the number of digits. I then display the individual digits and suppose to put the square of that digit next to it. Because the numbers are a string, I cannot square them. I tried using integers for my variable but do not know to access the numbers by digit in an integer with array. If someone could help me on that I'd really appreciate it. Here is the code I have so far. Thanks!

int digits, trials = 0, i = 0;
string number:
cout << "Enter the number of digits:";
cin >> digits;
cout << "Enter the number:";
cin >> number;

if (number.length() == digits) {
while ( trials < digits )
{
cout << number[i] << "\t" << SQUARE OF NUMBER HERE << endl;
i++; trials++;
}
}
You may use type casting to convert string to integer :-0
if am wrong expert will tell u.
(integer)number;
You can use boost::lexical_cast or stringstreams to do that.
declare a stringstream object.

 
std::stringstream ss;


to add a string to the stringstream.

1
2
3
4
5
6
// the 2 lines below reset the stringstream ensuring that it's internal flags are reset and that it contains no current string value
ss.clear(); 
ss.str(""); 

// add a string to the stringstream
ss << "some string value";


print the entire contents of the stringstream

 
cout << ss.str();
thanks a lot for the responds, but when I do change the string back to an integer, how do i access it's array to find each individual digits square?

For example the number 1234. To display the following:

1 1
2 4
3 9
4 16.

I tried doing this:
cout << number[i] << "\t" << pow( number[i] , 2 )<< endl;
i++; trials++;

but doesn't seem to work. Thanks.

Topic archived. No new replies allowed.