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.
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.
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
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 -
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.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; }
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.