-2
#include<stdio.h>

void main(void)
{   
    int n1,n2,r; // variables

    //this just simply add n1 and n2 and shows the result, i want it
    // to only allow numbers not alphabet
    printf("Enter the first number = ");
    scanf("%d",& n1);
    fflush(stdin);
    printf("Enter the second number = ");
    scanf("%d",& n2);
    fflush(stdin);
    r=n1+n2;
    printf("total = %d ", r);
}

as you can see my codes wont restrict anything, i want help in restricting the input of alphabets

bjskishore123
  • 6,144
  • 9
  • 44
  • 66
Xyroth
  • 1

1 Answers1

0

I believe the below question answers yours. Let me know if this helps!

It is using a while loop to ensure the input is only numbers, but could easily bee altered to be only chars. Also you can set your variable to be only numbers such as double or integer, the same way you can make it only a string.

Original Answered Link: How to make cin take only numbers

From Jesse Good's Answer

I would use std::getline and std::string to read the whole line and then only break out of the loop when you can convert the entire line to a 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 this helps!

Community
  • 1
  • 1
xxSithRagexx
  • 193
  • 1
  • 1
  • 13