Why is it "bad" to use cin for numeric variables?

Ian004

My current professor states on his syllabus:

"Never use cin >> to read directly into a numeric variable, like int or double or float. Read as a string (C or C++) and convert to a number using atoi or atof."

Is there a reason for this? At first I thought it is to avoid fail flags but if you just add input validation code isn't it fine to "cin >> myInt"?

Using his method, if they entered "4a5" and I did atoi wouldn't it still throw an error?

Thanks~

Lightness Races in Orbit

In general, there is nothing wrong with it at all. This advice would seem to be wrong.

In fact, by relying solely on stoi and friends, you lose any ability to control the conversion process. You might want to use these in some very domain-specific cases where you want to extract a specific number of characters and then attempt to convert them, but that's down to business logic.

Certainly, relying on antiquated code like atoi is even worse, what with its undefined behaviour on encountering many failure cases.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why is it bad to use short

Why is the use of rand() considered bad?

What objects to synchronize on? Why are local variables bad?

How bad it is to use global variables in nodejs?

Is it bad practice to use normal variables in react component?

Why can't use std::cin by setting std::cin.clear() after a wrong input?

Why use a numeric value in reinterpet_cast?

Why Thread.sleep is bad to use

Why is it bad practice to use from module import *?

Why is it bad practice to use links with the javascript: "protocol"?

Is it bad to use unicorn without nginx? why?

Why is it bad to use a function without parentheses in production?

(Why) is it bad to use ls -A to list hidden files?

Why tail-recursion is a bad use of recursion?

Why does nchar return the wrong values for large numeric variables in R?

How to use dplyr to convert variables from numeric to factor with unique levels

Why use variables for html attributes?

Why React Components being stored as variables or as state is bad design practice

Is it bad practice to use JavaScript Array.prototype.map with scoped variables

Whenever i use cin and use spaces in the string, why does it just skip through the whole thing?

Proper use of the cin object?

Why do STL numeric algorithms use 'op' rather than 'op='?

Why can't you use " ' " on a numeric value in a table?

When and why do I need to use cin.ignore() in C++?

why do I have to use cin.ignore when I not using getline()?

Why does this use of std::transform cause exc_bad_access

Why is it bad practice to use implicit id references in javascript?

Why is it bad practice to use an FCM Server Key on a Flutter/Android client?

Why is it a bad idea to use React Directly in HTML (not in a react enviroment)?