c - is there a way to restrict user to input only numerical values for the variables? -
#include<stdio.h> void main(void) { int n1,n2,r; // variables //this add n1 , n2 , shows result, want // allow numbers not alphabet printf("enter first number = "); scanf("%d",& n1); fflush(stdin); printf("enter second number = "); scanf("%d",& n2); fflush(stdin); r=n1+n2; printf("total = %d ", r); }
as can see codes wont restrict anything, want in restricting input of alphabets
i believe below question answers yours. let me know if helps!
it using while loop
ensure input numbers, bee altered chars
. can set variable numbers such double
or integer
, same way can make string
.
original answered link: how make cin take numbers
from jesse good's answer
i use std::getline
, std::string
read whole line , break out of loop when can convert entire line double.
#include <string> #include <sstream> int main() { std::string line; double d; while (std::getline(std::cin, line)) { std::stringstream ss(line); if (ss >> d) { if (ss.eof()) { // success break; } } std::cout << "error!" << std::endl; } std::cout << "finally: " << d << std::endl; }
hope helps!
Comments
Post a Comment