I'd like to know if there is a concise method for comparing a variable to a data type.

The following example is not a functioning piece of code, but the comment and the code below the comment should explain my question:

string inputString = "";
float inputFloat = 0.0;

cout << "Input a string: ";

getline(cin, inputString);
stringstream(inputString) >> inputFloat;

// Is there a way to compare a float variable to a string or float data type? 
if(inputFloat == string) { 
    cout << "inputFloat is not a float" << endl;
} else if(inputFloat == float) {
    cout << "inputFloat is a float!" << endl;
}
有帮助吗?

解决方案 2

What you need is just a simple check of return value of std::getline and operator>>:

std::cout << "Input a string: ";
std::string inputString = "";
float inputFloat = 0.0;
if (std::getline(std::cin, inputString) && 
    std::istringstream(inputString) >> inputFloat)  {
    std::cout << "Succesfully read float: " << inputFloat;
}
else {
    // TODO: either getline failed to read string or >> failed to extract float
}

note that std::istringstream(inputString) >> inputFloat constructs a temporary string stream and uses the appropriate overload of >> designed specially to extracting float values from it. Checking the return value additionally ensures that by the time the inputFloat is outputted, it has been successfully retrieved from the stream and contains valid value.

其他提示

Here:

stringstream(inputString) >> inputFloat;

When you do this, you are calling an operator>>(istream, float), so you either succeed to read a float there, or fail and load nothing. You can check for .fail() on the stringstream object to verify that.

Since you're calling that specific overload of operator>>, there's no possibility that you "loaded a variable of different type" into the inputFloat variable, or anything like that.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top