Hallo everyone, I have some problems with my assignment. I asked to provide some error-handling in my program. What I want to ask abou how we handle an input that isn't its type. For example i define a variable int a but we "accidentally" input a string or other type. How we can handle that error type ? Thank you before

Dani AI

Generated

Short note tied to the thread: wanted safe handling when a user types a string instead of an integer. showed stream-state checking and suggested reading text and parsing it. A modern, robust way to do the read-then-parse pattern is to read a full line and use std::from_chars (C++17) to parse integers without exceptions, detect leftover characters, and detect overflow.

#include <iostream>
#include <string>
#include <charconv>

int main() {
    std::string line;
    while (std::getline(std::cin, line)) {
        if (line.empty()) continue;
        int value;
        auto res = std::from_chars(line.data(), line.data() + line.size(), value);
        if (res.ec == std::errc() && res.ptr == line.data() + line.size()) {
            std::cout << "Parsed: " << value << '\n';
            break;
        } else if (res.ec == std::errc::invalid_argument) {
            std::cout << "Not a number\n";
        } else if (res.ec == std::errc::result_out_of_range) {
            std::cout << "Out of range\n";
        } else {
            std::cout << "Extra characters after number\n";
        }
    }
}

Notes and fallbacks: std::from_chars for integers is standard since C++17; floating-point support and library implementation can vary—check the [std::from_chars] documentation. If C++17 is not available, consider the C APIs like [strtol] (use endptr + errno) or std::stoi with try/catch (throws on invalid input). Always treat end-of-file as a separate condition in interactive programs and loop to reprompt until valid input or EOF.

std::from_chars
strtol

Recommended Answers

All 8 Replies

You must detect bad input condition then handle it. If possible, make recovery. For example:

int x;

    cout << "Type integer: ";
    if (cin >> x) {
        cout << "Thank you..." << endl;
    } else if (cin.eof()) { // end of stream
        cout << "cin closed." << endl;
    } else { // fail state (not a number}
        cin.clear(); // reset stream fail bit
        cout << "It's not a number." << endl;
        cin.ignore(1000,'\n'); // skip upto '\n'
    }

Of course, it's an example only. Try it then improve. There are lots of methods to cope with i/o errors...

One of the other approaches is to never accept input as a numerical type. Only accept input as a string. Then parse the string after input for it's validity as a numeric value and convert the string to the numerical type as desired if it's valid.

How I can convert it and know limit between numerical and string value ?

Please, don't divert your attention. I have presented the proper solution of your problem. Lerner's suggestion is not totally different approach: you need to handle stringstream input errors when process previously accepted string.

Can you differ is it a taste of a fish or a bread? If you get a string - it's a string, if you get a number - it's a numerical value ;)...

While it's perfectly legitimate to parse the input string with a stringstream and the >> operator, it is not mandatory. Manual parsing will work. It may be tedious, but it will work.

ArKM your code is work better, thank you^^. But I have some code that i don't understand.

} else if (cin.eof()) { //<== what this code mean ?
cout << "cin closed." << endl;

else { // fail state (not a number}
cin.clear(); // reset stream fail bit <== clear() and ignore() ?
cout << "It's not a number." << endl;
cin.ignore(1000,'\n'); // skip upto '\n'

Ah yes, how to make so we can back inputing the data after we handling the error ?
Thank you for your help >.<

Once you've determined the stream is in an unusable state you can try to figure out why. One of the reasons is that the end of file has been reached. You can check for that by called the eof() method of istreams. eof() will evaluate to true if end of file has been reached. You can clear the end of file flag with the clear() function. Then you can reuse the stream again. If the stream is unusable for some other reason than end of file, you can output a notice to the user, clear the fail bit with clear(), ignore whatever is in the stream and then reuse it again.

If you wrap all of this in a loop with a sentinnel flag as the conditional then you can change the value of the flag to false if valid input achieved to break out of the loop. Otherwise the loop keeps going until valid input is achieved.

Some addition to the wonderful Lerner's explanation.
As usually, closed user dialogue stream treated as the end of interaction condition (for example, the user press Ctrl+Z on Windows). That's why no stream recovery for eof case in my snippet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.