i'm new coding, please keep in mind before commenting.
so i've been trying coding while, , today went library , picked book called "programming in c++". i've written basic programs, have gotten stuck @ 1 point, have no idea how create function makes sure when user prompted double, enter valid. (if user enters character 'k', program breaks). searched here , on net, , there answers, more along line of "here's line of code works, insert x, y, z, it". , don't have enough experience know do. here sample mix of code question, , me failing try make work in program:
#include <iostream> #include <stdio.h> using namespace std; double getdouble () { double x; cin >> x; int valid = 0; while (valid == 0) { if (x == double) { return x; break; } else if (x != double) { cout << "invalid input! please input numerical value." << endl; cin.clear(); while (cin.get() != '\n') ; // empty loop } } return x; } now want use "cin << x" user input x, , make sure x double, , i'm failing quite hard @ this. if explain in manner clarifies each operation, grateful. example, don't know break function does, , cin.clear(), , cin.get() do. (i know duplicate, answers on other question not @ address i'm confused about, thank taking time read & answer this! :)
this seems close analog code (mostly) works:
double getdouble () { double x; cin >> x; // ver1: while( cin.fail() ) // or !cin.good() no trailing char check. while( cin.fail() || (cin.peek() != '\r' && cin.peek() != '\n')) { cout << "invalid input! please input numerical value." << endl; cin.clear(); while( cin.get() != '\n' ); // or cin.ignore(1000, '\n'); cin >> x; } return x; }
Comments
Post a Comment