0

How do make a condition in c++ that says you can't put letters from the alphabet? Well, I know how to do it manually but is there any way that you can't do it manually? I tried using the java code method but it didn't work(well it won't work really because it's from java not CPP)

if(choice == 'A-Za-z')
{
cout<<"No alphabet please"<<endl;
}
LickMe
  • 19
  • 2
  • 1
    'A-Za-z' is a mulitcharacter literal. It won't do what you want at all. Related: [https://stackoverflow.com/questions/3960954/multicharacter-literal-in-c-and-c](https://stackoverflow.com/questions/3960954/multicharacter-literal-in-c-and-c) – drescherjm Nov 26 '20 at 04:18
  • 1
    You need to use regex or if you're looking at a single character, you can look at the ascii value of the character by using `int(char)` and see if it's within 65-90 or 97-122 – Russell Islam Nov 26 '20 at 04:20
  • How to not manually put letters a to z but get the same result? – LickMe Nov 26 '20 at 04:20
  • Hint: Start with [`isalpha()`](https://en.cppreference.com/w/cpp/string/byte/isalpha). – tadman Nov 26 '20 at 04:21
  • 2
    @RussellIslam It's better to use constants like `'a'` and `'z'` than hard-coded raw ASCII numbers. These are much harder to get wrong. – tadman Nov 26 '20 at 04:29
  • Is choice a `char` in this code? – drescherjm Nov 26 '20 at 04:34

3 Answers3

3

You have to use isalpha() in C++.

if(isalpha(choice)){
 cout<<"No alphabet please"<<endl;
}

Refer isalpha() in cppreference or cplusplus for more info.

theWellHopeErr
  • 1,856
  • 7
  • 22
0

You can use Regex: /^[A-Za-z]+$/

#include <iostream>
#include <string>
#include <regex>

int main () {
    if (std::regex_match ("You Input", std::regex("^[A-Za-z]+$") ))
        std::cout << "string literal matched\n";
}

reference

renewss
  • 161
  • 1
  • 8
0

im only using .c file . sorry for the late answer.

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#pragma warning(disable:4996)

void main() {
char a;

do {
    rewind(stdin);
    printf("enter a value>");
    scanf("%c", &a);
    
} while (isalpha(a) == 0);
printf("invalid input");
}

so when the user inputs a character the loop will come to an end.