(String, …etc.) / integer, …etc.)

What would be the output of the program in case you do insert a text (String, …etc.) value instead of the numeric (integer, …etc.) values expected? And why ?
Hello gokhanyildirim99,

As I read your question what I come up with is new questions.

Do you mean in the program as num = string; or from user input as std::cin > num; and you enter a letter?

For the first example I am thinking that It would store the first character of the string in "num", but the value may not be what you think it is.

For the second example this is formatted input and "cin" expects a number to be entered from the keyboard. If you enter something other than a number, and this would include (.25) for a double, "cin" fails and becomes unusable the rest of the program until fixed.

Note: since (.25) starts with a non numeric character it is a problem. As a double it should be entered as (0.25) to be accepted as a number.

If you mean something else you will need to rephrase your question and show an example of code to demonstrate what you mean.

Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <limits>
using namespace std;

constexpr auto MaxStream {numeric_limits<streamsize>::max()};

int main()
{
    int n;

    while (true)
    {
        cout << "Number: ";

        if (cin >> n) break; // if you enter a valid int, end the loop

        // But suppose you entered HELLO (or too large an integer)
        // then the stream will "go bad".

        // eof is a special case since it means there will be no more input
        // (User may have entered Ctrl-Z on windows or Ctrl-D on *nix,
        //  or standard input may be redirected from a file.)
        if (cin.eof())
        {
            cout << '\n'; // needed on linux but not on windows (sigh)
            return 0;
        }

        cin.clear();  // stream state must be cleared before it's useable again
        cin.ignore(MaxStream, '\n'); // remove the offending line from the input buffer

        cout << "Try again.\n";
    }

    cout << "You entered: " << n << '\n';
}

Topic archived. No new replies allowed.