Is it better to input everything as a string and then convert to real #

This is a discussion on Is it better to input everything as a string and then convert to real # within the C++ Programming forums, part of the General Programming Boards category; Is it better to input everything as a string and then convert to real #s. How much of a trade ...

  1. #1
    Unregistered
    Guest

    Question Is it better to input everything as a string and then convert to real #

    Is it better to input everything as a string and then convert to real #s. How much of a trade off in performance is there with all of the extra code to change a string to a number and then back when saving the information to a file.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    If possible it's easier and takes less overhead to input numbers as numbers instead of as strings. If you input everything as strings then you have to break the strings up into individual number strings and convert them to the numbers you want.

    That can be very accident prone and will make your code larger, both of which are bad. Sometimes it's the only way, but in most cases you can do individual input.

    -Prelude

  3. #3
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    If you reading from a stream and don't want to have to read into a string then convert you could test the streams fail state after input -

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        double d;
        cin>>d;
        while(cin.fail())
        {
            cin.clear();
            cin.ignore(80,'\n');
            cin >> d;
        }
        cout << d;
        return 0;
    }
    If there is invalid input the streams fail state will be set and you can re-input the data. If you're reading from a file this method won't help (as you can't ask the file for another input) but you can tell if and when there has been a bad input.

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    A compromize is to use some form of data validation (fail() or strings with conversion or whatever) when requesting user input but not when using file input--which assumes all data in file is valid--which is probably correct if you made the file, but may not be true if you didn't. There is no system that is failproof and no system that is real "programmer" friendly. It's a series of tradeoffs.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21