Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 27th, 2006, 5:21 AM   #1
Cool1Net6
Newbie
 
Cool1Net6's Avatar
 
Join Date: Aug 2005
Location: Florida, U.S.A.
Posts: 10
Rep Power: 0 Cool1Net6 is on a distinguished road
Convert String to Int

In a recent contest, the problem was to reverse the digits of a number and add that new number to the old number to come up with a newer number. I had the knowledge to reverse the digits of a number by converting the original number to a string and swapping the positions of each character, but to add this new number to the original number, I needed to convert the new number back to an int. I lost the competition because I lacked this knowledge.

How do you convert a String to an Int?

-Cool-
__________________
"Give a programmer enough pizza and coke they'll do anything you want."
Cool1Net6 is offline   Reply With Quote
Old Nov 27th, 2006, 5:43 AM   #2
kruptof
Professional Programmer
 
kruptof's Avatar
 
Join Date: May 2006
Location: UK - London
Posts: 333
Rep Power: 3 kruptof is on a distinguished road
you could of done string.c_str() which would return you the string in an const char* format then you could loop through that new constant array of characters and convert each one to an number use atoi or something else, some else reccommended.
__________________
Quote:
When I was young it seemed that life was so wonderful,a miracle, oh it was beautiful, magical.
Now watch what you say or they'll be calling you a radical,a liberal, oh fanatical, criminal. Oh won't you sign up your name,we'd like to feel you're acceptable, respectable, oh presentable, a vegetable
kruptof is offline   Reply With Quote
Old Nov 27th, 2006, 7:10 AM   #3
Soulstorm
Hobbyist Programmer
 
Soulstorm's Avatar
 
Join Date: Jan 2006
Location: Menidi, Athens, Greece
Posts: 243
Rep Power: 3 Soulstorm is on a distinguished road
The easiest way to do it is to use a stringstream

example:

cpp Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. int main (int argc, char * const argv[]){
  5. std::stringstream s("2903");
  6. int i;
  7.  
  8. s >> i;
  9. std::cout << i+100;
  10.  
  11.  
  12. return 0;
  13. }
Probably a bad example, but it should give you an idea on what to do. Give to an std::stringstream the number you want as a constant character, or an std::string and extract it to an integer or enything else you want.

You could also use atoi(), but using stringstreams will be a lot easier for you and a lot more comprehensive.

The STL has many things you should read when you encounter a problem. In many occasions, the STL solves the problem. Check this out for a reference.
__________________
Project::Soulstorm (personal homepage)
Soulstorm is offline   Reply With Quote
Old Nov 27th, 2006, 7:51 AM   #4
Lesliect6
Programmer
 
Join Date: Aug 2005
Posts: 68
Rep Power: 4 Lesliect6 is on a distinguished road
Hello Coll1Net6,

Converting a string to an int is very easy, having in mind that a string is only a representation of a number in the ASCII chart. Having also in mind that a string is nothing more than an array of chars, you can easily manipulate each individual character. So, if your string is composed only of numbers in string format (like '4' or '6'), all you have to do is :

int number = string[x] - 48;

where x is the index of the char you want converted to int.

And the job is done.
Lesliect6 is offline   Reply With Quote
Old Nov 27th, 2006, 8:11 AM   #5
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Leslie, your method is contingent upon the characters being in an ASCII representation. Such is not always the case. One should use string streams, as recommended, or perhaps strtol or similar. Atoi is not a good choice because errors are indistinguishable from converting the value, zero (and other badnasty results).
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Dec 7th, 2006, 12:47 PM   #6
pegasus001
Hobbyist Programmer
 
pegasus001's Avatar
 
Join Date: Nov 2006
Location: 163H
Posts: 215
Rep Power: 3 pegasus001 is on a distinguished road
int string_to_int(string number)
{
int num = 0;
int temp = 1;

for (int i = number.length; i >= 0; i--)
{
num += atoi(number[i]) * temp;
temp *= 10;
}

return num;
}
pegasus001 is offline   Reply With Quote
Old Dec 7th, 2006, 1:38 PM   #7
Narue
Professional Programmer
 
Narue's Avatar
 
Join Date: Sep 2005
Posts: 419
Rep Power: 4 Narue is on a distinguished road
>for (int i = number.length; i >= 0; i--)
That's an off-by-one error and a syntax error. You want to start at number.length() - 1.

>num += atoi(number[i]) * temp;
Okay, number is a string, so number[i] is a character. That alone is a type mismatch. You could take the address of that character because atoi expects a C-style string (any number of characters terminated with '\0'), but the string class doesn't guarantee that internal representation.

The good news is that your algorithm only expects single characters at a time, so you can use the subtraction trick to turn something like '5' into 5:
num += (number[i] - '0') * temp;
Then your only problem is when the string doesn't represent a valid integer.
__________________
Even if the voices aren't real, they have some pretty good ideas.
Narue is offline   Reply With Quote
Old Dec 7th, 2006, 1:58 PM   #8
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Are you people reading the responses? ATOI is not a good thang. Here's a quote from cplusplus (emphases mine):
Quote:
Return Value.

The converted integer value of the input string.
On overflow the result is undefined.
If an error occurs 0 is returned. (How do you know whether it's an error, or a conversion of zero?)
Using this is essentially dereliction, like using 'gets'.

I have modified Soulstorm's code to present some alternatives. All are easy. It's certainly preferable to looping through a set of characters and calling atoi, when there's no guarantee that each of the characters is convertible.
#include <iostream>
#include <sstream>
#include <string>

int main (int argc, char * const argv[])
{
    int myInt;
    std::string aString = "3092";
    char cString [] = "2903";

    // Use a C string
    std::stringstream withCString (aString.c_str ());
    // Use another C string
    std::stringstream withCString2 (cString);
    // Use a string-class string
    std::stringstream withString (aString);

    withCString >> myInt;
    std::cout << myInt << std::endl;
    withCString2 >> myInt;
    std::cout << myInt << std::endl;
    withString >> myInt;
    std::cout << myInt << std::endl;;
   
    return 0;
}
Output:
Quote:
3092
2903
3092
EDIT: Woops, was off keying in the code while Narue posted.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Dec 9th, 2006, 12:42 PM   #9
pegasus001
Hobbyist Programmer
 
pegasus001's Avatar
 
Join Date: Nov 2006
Location: 163H
Posts: 215
Rep Power: 3 pegasus001 is on a distinguished road
Quote:
Originally Posted by Narue View Post
>for (int i = number.length; i >= 0; i--)
That's an off-by-one error and a syntax error. You want to start at number.length() - 1.
I forgot, about that.

Quote:
Originally Posted by Narue View Post
>num += atoi(number[i]) * temp;
Okay, number is a string, so number[i] is a character. That alone is a type mismatch. You could take the address of that character because atoi expects a C-style string (any number of characters terminated with '\0'), but the string class doesn't guarantee that internal representation.

The good news is that your algorithm only expects single characters at a time, so you can use the subtraction trick to turn something like '5' into 5:
num += (number[i] - '0') * temp;
Then your only problem is when the string doesn't represent a valid integer.
Well we can arrange that with a switch statement, what do you think????:beard:
pegasus001 is offline   Reply With Quote
Old Dec 9th, 2006, 1:50 PM   #10
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
I think you're not paying attention to the responses. Next question?
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
C# corruption!!! Kilo C++ 32 May 21st, 2006 9:44 PM
Array issues :( Alo Tsum Java 10 Nov 26th, 2005 6:45 PM
Convert a string to unicode string sma_soft Delphi 3 Nov 16th, 2005 6:06 AM
replace space with ' * ' TecBrain C++ 15 Apr 13th, 2005 1:32 PM
function solomon_13000 Java 6 Apr 3rd, 2005 12:42 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 6:46 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC