(08-01-2014, 11:32 PM)dropzon3 Wrote: Code:
#include <cstdlib>
int main(int argc, char* argv[]) {
int input;
std::cin >> hex >> input;
}
Using scanf is cleaner imo and C++ supports that function...
Explain how it would be cleaner? At the least, it is much less typesafe than what you would and should normally do if you're writing in C++. Additionally, that function has to do the following:
1. Parse the format string to determine the types and variable arguments to parse from an args list
- Look for occurrences of %
2. Determine all the attributes/specifiers in the format designator (%7.4lf for example)
3. Read the characters from the standard input buffer until a character that isn't right for the specified format from the input string is found
4. Convert these characters into the proper binary format for the specified type
5. Load the binary data into the variable referenced by the pointer parameter(s) passed in, following the format string
This process repeats until the variable arguments have all been assigned to, which is determined by the format string (the only way to determine how many variable arguments were actually passed in).
It's a huge and very ugly function.
However, in either variation scanf() or std::cin, are you correctly handling invalid input for the standard input.
Here's what I was looking for somewhat:
Code:
#include <iostream>
#include <string>
#include <limits>
int main()
{
int x;
{
while (!(std::cin >> std::hex >> x))
{
std::cout << "Invalid input, try again..." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::string tmp; getline(std::cin, tmp);
}
std::cout << x << std::endl;
}