Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we always check if input fails but not output?

Tags:

c++

c++11

Why do we always do this

if (cin >> var)

but never do this

if (cout << var)

Aren't we suppose to check if it succeeded or not?

like image 249
user2030677 Avatar asked Jan 12 '14 16:01

user2030677


People also ask

How do you check if input is not a character?

You can use num. isnumeric() function that will return You "True" if input is number and "False" if input is not number. You can also use try/catch: try: val = int(num) except ValueError: print("Not an int!")

How do you check if an input is an int C++?

Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.

Why is gets not taking input in C?

scanf usually leaves a newline in the input stream that will cause problems for fgets. Parse the input for an integer with sscanf and check the return to make sure an integer was input. Show activity on this post. Never use gets() .


Video Answer


2 Answers

It's easy to generate End Of File on input. For example, the input might come from a file. Or an interactive user might indicate EOF in some command interpreter specific way (e.g. Ctrl Z in Windows, or Ctrl D in *nix).

Generally that causes input failure.

For cin >> var which is formatted input, there can also be failure to interpret the input text as a specification of a value of the relevant type.

None of this applies to output.

Output can fail, but generally only due to pretty catastrophic reasons such as the storage unit becoming full.

like image 167
Cheers and hth. - Alf Avatar answered Nov 09 '22 03:11

Cheers and hth. - Alf


The premise is wrong: not all writes go unchecked.

As an example of checked writes, consider a database. Before answering OK to a commit request, a database will generally ensure that the data has been correctly written to disk or duplicated (and acknowledged) to another instance.

Therefore, it is less that software does check writes, and more than writes are checked differently than reads: a failed read mean that the program cannot continue (in general) because it is lacking data; on the other hand, the program can continue after a failed write for it already has the data!

Thus, the only writes that are checked are those which the program guarantee to check, such as the database writes to a hard-disk that ensure the durability of the data that the software promises. On the other hand, writes to log files or console screens are rarely (if ever) checked: log files are generally not supposed to get in the way (and they are logged asynchronously) and if a write to the console screen fails the user will likely replay the command anyway or the next program in the pipe will fail itself...

like image 42
Matthieu M. Avatar answered Nov 09 '22 02:11

Matthieu M.