I've just learned the basics of c-strings and how to read line oriented input. I noticed that fail bits are set for each function. However, not every problem sends a fail bit, so I thought this would be a good exercise to try and target two user input errors:
- The user enters no input
- The user enters more input than the allocated number of elements
/*Simple Error handle using get() and getline() *with too much input or no input on c-style strings */ #include <iostream> #include <string> #include <limits> int main() { const int size = 10; std::cout << "Please enter your name and hit enter. Then have your friend do the same\n\n"; //Using get() std::cout << "Your name: "; char name1[size]; while (!std::cin.get(name1, size) || std::cin.get() != '\n') { if (!std::cin) { std::cout << "No input\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } else { std::cout << "Name entered was too large for allocated memory...\n"; } std::cout << "Try again: "; } //using getline() std::cout << "Your friends name: "; char name2[size]; while (!std::cin.getline(name2, size) || name2[0] == NULL) { if(name2[0] == NULL){ std::cout << "No input\n"; } else { std::cout << "Name entered was too large for allocated memory...\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } std::cout << "Try Again: "; } std::cout << "\nNAME1: " << name1 << " NAME2: " << name2 << "\n"; std::cin.get(); return 0; }
istream
don't go well with each other. I'm afraid you probably spent your time for nothing. C style char arrays are effective in solving some problems, but getting user input is the worst case scenario for them.\$\endgroup\$iostream
s are generally rarely used in C++. Usually people read from sockets, and libraries have dedicated API for reading only certain amount of information from it. I believe that writing good generic data structures and writing algorithms (generic or not) would be the best route of learning C++. Those probably cover most parts of C++ as well, at least most used ones.\$\endgroup\$