Page 2 of 3 FirstFirst 123 LastLast
Results 11 to 20 of 21

Thread: Convert C++ String to Integer

  1. #11
    Join Date
    Jul 2005
    Beans
    1,535
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Convert C++ String to Integer

    What an old thread to suddenly revive. Anyways,

    Quote Originally Posted by aks44 View Post
    As noted previously, boost::lexical_cast is a very good C++ solution (the cleanest IMHO), unless for some reason you don't want to use boost in which case std::stringstream is the way to go.

    The big advantage of boost::lexical_cast is that it throws an exception on error, no need to add clutter for error checking.
    Boost's lexical cast is just a wrapper on top of stringstream; stringstreams will throw exceptions that you can catch so I don't understand why you consider it an advantage to boost. I agree 100% that lexical_cast cleans up the syntax a ton, but it doesn't really add anything else.

    Herb Sutter has a great article about string formatters that is very relevant to this thread: http://www.gotw.ca/publications/mill19.htm
    When I invented the Web, I didn't have to ask anyone's permission.
    ~Tim Berners-Lee on Net Neutrality
    -------------------------------------
    Visit the Ubuntu Programming IRC-channel at #ubuntu-programming (chat.freenode.net).

  2. #12
    Join Date
    May 2007
    Location
    Paris, France
    Beans
    927
    Distro
    Kubuntu 7.04 Feisty Fawn

    Re: Convert C++ String to Integer

    Quote Originally Posted by hod139 View Post
    stringstreams will throw exceptions that you can catch so I don't understand why you consider it an advantage to boost.
    Granted, stringstreams can throw if you throw (!) more garbage in, namely calling the exceptions() method. But by default they don't.

    I guess I'm just very exception-centric when it comes to error reporting, since exceptions lead to much cleaner & stable code than manually checking return codes IMHO (you can hardly avoid an exception by inadvertance...).


    I guess I should have written
    Quote Originally Posted by aks44 View Post
    The big advantage of boost::lexical_cast is that by default it throws an exception on error, no need to add clutter for error checking.
    Not even tinfoil can save us now...

  3. #13
    Join Date
    Sep 2009
    Location
    Weedsport, New York, USA
    Beans
    15
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Convert C++ String to Integer

    First, I admit I'm a beginner. Second, I admit that I am in over my head. This is part of a learning exercise I came up with on my own and am having trouble fine tuning. The rest of the program is exactly right; this one problem is giving me hell!

    I am trying to convert a 4 digit int to a string, loop to the end of the string ('/0'), then backtrack to obtain the last 2 places and convert those back to (eventually!) a single int. The reason for this is to separate the numbers without prior knowledge of the numbers.

    Here is my first attempt:

    Code:
    int fourDigitIn, tensPlace, onesPlace, twoDigitOut;
    int a = 0;
    
    char iterator[];
    
    cin >> fourDigitIn;
    
    itoa (fourDigitIn, iterator, 10);
    
    while (iterator[a] != '/0')
    { a++ }
    
    const char ten = iterator[a-2];
    const char one = iterator[a-1];
    
    tensPlace = atoi (&ten);
    onesPlace = atoi (&one);
    
    twoDigitOut = tensPlace + onesPlace;
    
    cout << twoDigitOut << endl;
    Output from the above bit of code, when the user inputs 2956, for example, returns a value of 62 to twoDigitOut rather than the expected 56. Further testing indicates that the above code will always add the ones back into itself twice rather than the expected once, so that user input of 6789 will return 98 rather than 89, user input of 1234 will return 38 rather than 34, and so on.

    Ok, so I have something odd going on here. To attempt to combat this problem, I tried:

    Code:
    twoDigitOut = (tensPlace * 10) + onesPlace;
    The return on that for the same user input of 2956 is 566. This obviously didn't work, either.

    I tried to comment out the lines that set the onesPlace variable and output the tensPlace only, like this:

    Code:
    int fourDigitIn, tensPlace, onesPlace, twoDigitOut;
    int a = 0;
    
    char iterator[];
    
    cin >> fourDigitIn;
    
    itoa (fourDigitIn, iterator, 10);
    
    while (iterator[a] != '/0')
    { a++ }
    
    const char ten = iterator[a-2];
    //const char one = iterator[a-1];
    
    tensPlace = atoi (&ten);
    //onesPlace = atoi (&one);
    
    twoDigitOut = tensPlace;// + onesPlace;
    
    cout << twoDigitOut << endl;
    My reasoning was that if multiplying my tensPlace by 10 and adding the onesPlace to it produced 566, and that if adding the tensPlace and onesPlace produced 62, then my tensPlace was producing the needed two digit output I desired. However, the return on that same user input of 2956 now produced an output of 25. Checking other input repeatedly shows me that the code now ignored the ones place completely and returned half of the resulting tens value. Any input with 5 in the tens place produced 25, any input with 7 in the tens place produced 35, and so on.

    Can anyone help me figure out what I need to do to settle this?

    Thank you!
    Last edited by elfinkind; September 26th, 2010 at 07:56 PM. Reason: I mis-typed part of my code, didn't want everyone to think I was completely stupid, only partly...

  4. #14
    Join Date
    Apr 2005
    Location
    Hampshire, UK
    Beans
    1,273

    Re: Convert C++ String to Integer

    Quote Originally Posted by elfinkind View Post
    snip
    This doesn't compile, here: you have no size for the iterator array, and the a++ needs a semicolon. Please post the full, compileable code

  5. #15
    Join Date
    Sep 2009
    Location
    Weedsport, New York, USA
    Beans
    15
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Convert C++ String to Integer

    Quote Originally Posted by GeneralZod View Post
    This doesn't compile, here: you have no size for the iterator array, and the a++ needs a semicolon. Please post the full, compileable code
    Yep, like I said when I edited it - I managed to mis-type some of it...

    Ok, try it with those fixes in place, including the entire code as it appears in Microsoft Visual C++ 2010 Express (and while I'm at it, I'll comment it so you know what I was thinking):

    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
    int fourDigitIn, tensPlace, onesPlace, twoDigitOut; 
    int a = 0, b;  
    
    char iterator[50];  // declare character array with WAY more positions than I need, 
    just because
    
    cin >> fourDigitIn;  // request input from user - don't cheat, stay within the scope 
    of the array
    
    itoa (fourDigitIn, iterator, 10);  // this changes the int fourDigitIn to char iterator. 
    the 10 is there to indicate that it needs to be stored as a base ten number in the array
    
    while (iterator[a] != '/0') // this counts int a up through the array positions until it 
    reaches the end, or null so I can work backward through it to the last two numbers
    { a++; }  
    
    const char ten = iterator[a-2]; // here I declare two const char variables and assign 
    them the values I need from the iterator array
    const char one = iterator[a-1];  
    
    tensPlace = atoi (&ten); // here I change each const char back to int values. my intent 
    here was to acquire the value of the tens position and the ones position
    onesPlace = atoi (&one);  
    
    twoDigitOut = tensPlace + onesPlace;  // here I attempted to combine the two ints 
    into a single number
     
    cout << twoDigitOut << endl; // output the result for validation
    
    cout << "This is just to pause the console so output can be checked." << endl;
    cout << "Press any key followed by enter to end: " << endl;
    
    cin >> b;
    
    return 0;
    
    }
    Knowing my luck, I'm just stuck because I'm using the express version, and it won't do everything I need it to do. That would be par for the course...

  6. #16
    Join Date
    Apr 2005
    Location
    Hampshire, UK
    Beans
    1,273

    Re: Convert C++ String to Integer

    Quote Originally Posted by elfinkind View Post

    Code:
    tensPlace = atoi (&ten); // here I change each const char back to int values. my intent 
    here was to acquire the value of the tens position and the ones position
    onesPlace = atoi (&one);
    atoi expects a null-terminated string, which &ten and &one are not (they are pointers to a single char).

    Edit:

    Also, a null char is \0, not /0

  7. #17
    Join Date
    Sep 2009
    Location
    Weedsport, New York, USA
    Beans
    15
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Convert C++ String to Integer

    Quote Originally Posted by GeneralZod View Post
    atoi expects a null-terminated string, which &ten and &one are not (they are pointers to a single char).
    That brings me back to my original question - can you help me with the code I will need to make this happen? I feel that I explained myself quite well, but if there is still doubt, I will attempt to explain again in better detail. I also stated from the outset that I am a beginner, and that was intended to mean that I need more than just a hint - I have searched and searched, and this was the best I could come up with on my limited experience.

    Thanks!

  8. #18
    Join Date
    Oct 2006
    Location
    Tucson, AZ
    Beans
    1,420
    Distro
    Xubuntu 10.04 Lucid Lynx

    Re: Convert C++ String to Integer

    Quote Originally Posted by elfinkind View Post
    That brings me back to my original question - can you help me with the code I will need to make this happen? I feel that I explained myself quite well, but if there is still doubt, I will attempt to explain again in better detail. I also stated from the outset that I am a beginner, and that was intended to mean that I need more than just a hint - I have searched and searched, and this was the best I could come up with on my limited experience.

    Thanks!
    Why exactly are you using strings to get the last two digits? It would be much simpler to just do something do a something like
    Code:
    twoDigitOut = fourDigitIn % 100
    and then format the output to 2 places with leading zeros...

    Lloyd B.
    Don't tell me to get a life.
    I had one once.
    It sucked.

  9. #19
    Join Date
    Sep 2009
    Location
    Weedsport, New York, USA
    Beans
    15
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Convert C++ String to Integer

    Ok, will try that, and see what happens.

    Thank you!
    Last edited by elfinkind; September 27th, 2010 at 09:51 AM.

  10. #20
    Join Date
    Sep 2010
    Beans
    18

    Re: Convert C++ String to Integer

    I'm only a beginner in programming too, but I recently did a C++ bit of code that applies. Note that the number I read in was from a large text file, however, I think you could just put in the name of your string where "AddressOfNumberInTextFile" is.

    I initialised imgNum earlier in the code as an integer. which is why "numberStream >> imgNum" converts the character stream to a number successfully.

    Code:
    string numberString = bufferString.substr(AddressOfNumberInTextFile);
    
    // stringstream provides an interface to manipulate strings as if they were input/output streams. 
    stringstream numberStream(numberString); 
    
    if((numberStream >> imgNum).fail()){    // Convert stream to integer
             cout << "ERROR: Failed string to integer conversion";
    }
    cout << "imgNum integer: " << imgNum << endl;

Page 2 of 3 FirstFirst 123 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •