Testing the input if it is numeric or not - c

I wrote a C program wherein I am accepting a numeric input from the user. However, if the user inputs a character, then I have to show that it is an invalid input and make the user enter a number again. How do I achieve this? I am writing the program using gcc compiler in Ubuntu. The search results on Google suggest to use isalpha function...however, it is not available in the libraries I guess.
I also tried the below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void main()
{
system("clear");
if (isdigit(1))
printf("this is an alphabet\n");
else
printf("this is not an alphabet\n");
}

You will need to use scanf to get user input with %d as you want to scan an integer. In your case, scanf will return 1 on sucessfull scanning.
int num;
//loop to prompt use to enter valid input
while(scanf("%d",&num)==0) //scanning an integer failed
{
printf("invalid input ! Try again\n");
scanf("%*s"); //remove the invalid data from stdin
}
The functions isalpha() and isdigit() works when you are getting a character input using %c in the scanf. If you want to scan input using %c , then you can simply check like what you have done in your code provided that you get input using %c. Note that character 1 ('1') is note equal to integer 1 . Characters have their integer values as represented by the ASCII table. Your program to prompt the user again when the user enters anything other that a number using %c will look like this:
char ch;
while(1){
printf("Enter a number\n");
scanf(" %c",&ch);
printf(Your input is %c\n",ch);
if(isdigit(ch))
{
printf("This is a number\n");
break;
}
else
printf("This is not a number. Invalid input\n");
}

I tried the below code which worked fine..using isdigit()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void main()
{
system("clear");
char str[1];
printf("Enter a number\n");
scanf("%s",str);
printf("What you entered was %s\n",str);
if(isdigit(str[0]))
printf("this is not an alphabet\n");
else
printf("this is an alphabet\n");
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include<ctype.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
bool check=true;
while(check)
{
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
{
printf("%c is an alphabet.",c);
check=true;
break;
}
else
{
printf("%c is not an alphabet.",c);
check=false;
}
}
return 0;
}

You can write your own. It's better to check digits since there're less cases for digits.
bool isDigit(char c) {
bool rtn = false;
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
rtn = true;
break;
default:
rtn = false;
break;
}
return rtn;
}

Related

Read a single user input using scanf and convert it into appropriate data type

I have a program that reads user input as such:
char c;
scanf("%c", &c);
and then checks if it is a digit:
if(isdigit(c)) {
int f = atoi(c);
return f;
}
switch(c) {
case 'q':
exit(1);
break;
...
}
...
Example program:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char c;
scanf("%c", &c);
if(isdigit(c)) {
int f = atoi(&c);
printf("f: %d\n", f);
return f;
}
switch(c) {
case 'q':
printf("q\n");
return -1;
break;
}
return 0;
}
However when I enter, for exmaple, 10 then the input becomes 1 and 0 and \n. I want 10. How do I read "10" and "100" and "4" for example as well as other characters such as "q"?
char variables are only capable of saving one character. So if you want to have multiple characters (numbers are also characters) in a char variable you have to use string or char VARIABLE[size] . For example: char variable[10] can save up to 10 characters. But then you can't use isdigit() in that way anymore. Instead you have to use a loop to check each character of the string.

I can't input a string in c

So I've tried so much but I can't input a string even using: fgets, gets, scanf, and scanf("%[^\n]%*c",pharse). I need a string with the spaces. It just jumps the code line of input I think.
Please answer with a explanation of why it doesn't work
https://repl.it/#YashKumar11/String#main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
const int DIMMAX=100;
char pharse[DIMMAX+1];
int stringLength;
int choice=0;
while(choice != '5'){
printf("1)Enter a new pharse.");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5)\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\n=====================\n");
scanf ("%[^\n]%*c",pharse); //<-----------------------It jumps here
printf("\n=====================\n");
stringLength = strlen(pharse);
printf("%s",pharse);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
printf("\nNot a valid option.\n\n");
break;
}
}
return 0;
}
the statement to input the parase fails because the input for choice leaves a \n in the input stream.
When the second call to scanf() is made, it immediately returns (with a returned value of 0) because the first character input is \n.
suggest following each call to scanf() with:
int ch;
while( (ch = getchar()) != '\n' && ch != EOF );
that also implies that the format string of the second call to scanf() should have the %*c removed.
Your problem is not in the line that you try to read the string, but in the previous call to scanf()
scanf() was written to scanf formatted input. Keyboard input is not that. It can be everything except formatted. The user has over 100 keys to choose from
When the user types a '1' to input a phrase scanf() does not consume the newline. In fact the user can type 1 here we go to enter some text!
and then ENTER. And scanf() will be ok with just the '1'. The rest of the chars would be left there for the program to read. scanf() has no way to know what is left there.
Also scanf() return an int with the number of values read, and it can be zero if the user entered no digits. And you did not tested in your code.
Compare with your code a bit modified below
#define DIMMAX 100
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char phrase[DIMMAX + 1];
int stringLength;
printf("1) Enter a new phrase");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5) Exit\n\nOption: ");
fgets(phrase, DIMMAX, stdin);
while (phrase[0] != '5')
{
switch (phrase[0]) {
case '1':
printf("\n=====================\n");
fgets(phrase, DIMMAX, stdin);
printf("\n=====================\n");
stringLength = strlen(phrase);
phrase[strlen(phrase) - 1] = 0; // deletes the '\n'
printf("Phrase: '%s', len = %zd\n\n", phrase, strlen(phrase));
break;
case '2':
break;
case '3':
break;
case '4':
break;
case '5':
break;
default:
printf("\n'%c' (dec %d) is not a valid option.\n\n",
phrase[0], phrase[0]);
break;
}
printf("1) Enter a new phrase");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5) Exit\n\nOption: ");
fgets(phrase, DIMMAX, stdin);
}; // while()
return 0;
}
Maybe it helps to understand.
Note that instead of stopping rigth at the digit, like scanf(), fgets() read up to and including the newline, so if you are using printf() and not puts() to output it, you must take the last byte off the string read

How to get rid of the space/ enter of the input buffer in vim?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct st{
char n[100]; //Name
char d[100]; //lastname
} arr[4];
void add(int *c, struct st l[])
{
int i =*c;
int arrSize =sizeof(arr) / sizeof(arr[0]);
if((*c)<arrSize)
{
printf("Enter a name :\n");
fgets(l[i].n, 100,stdin);
printf("Enter lastname :\n");
fgets(l[i].d,100,stdin);
printf(" SUCCESS. Person was added\n");
}
}
int main(void)
{
int ct =0;
int *ctPointer=&ct;
char response ;
char endWhileloop =0;
while(endWhileloop==0)
{
printf("To add a person to the list hit 'a' \n");
printf("to end program enter 'q'\n");
fgets(&response,2,stdin);
fseek(stdin,0,SEEK_END);
switch(response)
{
case 'a':
add(&ct, arr);
break;
case 'Q':
endWhileloop=1;
break;
}
}
printf("\nbye.");
return 0;
}
I am trying to run my code in an older version of Vim(maybe an older version of C) for my school. Unfortunately I am not certain what version they are running
Surprisingly, my code works from home using vim and eclipse. but not from school
:I tried---> fgets, scanf("%[^\n]s",name) , scan( %c,&name), fseek(stdin,0,SEEK_END),flush(stdin);
But nothing has worked for me. I would like to know of some possible solutions.
When I run my code from school(not home), after I enter 'a' my code prints: Enter name..(line in between) Enter last name.
Without taking an input.
Place this line instead of fseek
After getting the option you are not clearing the input buffer. so this is the reason for the not getting the first input.
After entering the first input new line will be there in input buffer. After processing first input then buffer will give the \n.
So place this line after getting the option. Declare the variable int c;
while((c=getchar()) != '\n' && c!= EOF );
Then make the case into like this,
case 'a': case 'A':
...
...
case 'q': case 'Q':
...
...
For getting the option you can use simply the scanf like this.
scanf(" %c",&response);

C program switch statement

I'm new to programming in C. I have a quick question about Switch Statements.
I have a menu that presents a list of options like so:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
struct Video {
char name[1024]; // Yvideo name
int ranking; // Number of viewer hits
char url[1024]; // YouTube URL
};
struct Video Collection[MAX];
int tail = 0;
//-- Forward Declaration --//
void printall();
void insertion();
void savequit();
void load();
void branching(char);
void menu();
int main()
{
char ch;
load(); // load save data from file
printf("\n\nWelcome\n");
do {
menu();
fflush(stdin); // Flush the standard input buffer
ch = tolower(getchar()); // read a char, convert to lower case
branching(ch);
} while (ch != 'q');
return 0;
}
void menu()
{
printf("\nMenu Options\n");
printf("------------------------------------------------------\n");
printf("i: Insert a new favorite\n");
printf("p: Review your list\n");
printf("q: Save and quit\n");
printf("\n\nPlease enter a choice (i, p, or q) ---> ");
}
void branching(char option)
{
switch(option)
{
case 'i':
insertion();
break;
case 'p':
printall();
break;
case 'q':
savequit();
break;
default:
printf("\nError: Invalid Input. Please try again...");
break;
}
}
so far entering 'i' (for inserting a new entry) and q (for save and quit) work perfectly. However every time I enter 'p' I get the default case. (Error: Invalid Input. Please try again...). What is it that I am doing wrong? I believe the syntax for the switch is correct? I've tried changing the 'p' to a different letter and I still got the the default case. Here is my printall() method if that helps...
void printall()
{
int i;
printf("\nCollections: \n");
for(i = 0; i < tail; i++)
{
printf("\nName: %s", Collection[i].name);
printf("\nRanking (Hits): %d", Collection[i].ranking);
printf("\nURL: %s", Collection[i].url);
printf("\n");
}
}
What about something like:
char b[5];
do {
menu();
if(fgets(b,5,stdin)==NULL)
return -1;
ch = tolower(b[0]); // read a char, convert to lower case
while(strlen(b)>=4&&b[3]!='\n'){
check=fgets(b,5,stdin);
if(check==NULL)
return -1;
}
branching(ch);
} while (ch != 'q');
You can output the invalid char in your default case. That may help you understand how your input are handled.
default:
printf("\nError: Invalid Input ('%c'). Please try again...", option);
break;
fflush(stdin) is undefined as fflush is define only for output streams. To clear the newline char, you can simply use another getchar().
Try this for the loop part:
do {
menu();
ch = tolower((unsigned char)getchar());
getchar();
branching(ch);
} while (ch != 'q');

how to create an interactive menu in C that moves from one function into another without redrawing the menu

My goal is to produce a program that will take a file as input and "encode" the text within by shifting the characters ahead 3 (so 'a' would be come 'd'). It should produce an output file with the encoded text. The menu is to take user input and execute the function that is assigned to the number selected.
I'm early on at creating this program, but running short on time and am struggling with how to structure it. Currently, I have the menu displaying, but when a sub function is called, it displays but then the menu overwrites it and I can't figure out why. Any help would be appreciated. Here is the code I have so far...
#include <stdio.h>
#define INPUT_FILE 1 //define statements
#define OUTPUT_FILE 2
#define NUM_TO_SHIFT 3
#define ENCODE 4
#define QUIT 0
int menu(); //function prototypes
int input();
int output();
int shift();
int encode();
void quit();
int main()
{
int choice; // main variables
char user_filename[100];
choice = menu(); // get user's first selection
while(choice != QUIT) //execute so long as choice is not equal to QUIT
{
switch(choice)
{
case INPUT_FILE:
printf("Enter the filename of the file to encode:\n");
printf("(hit the Enter key when done)\n");
gets(user_filename);
break;
case OUTPUT_FILE: output();
break;
case NUM_TO_SHIFT: shift();
break;
case ENCODE: encode();
break;
case QUIT: quit();
break;
default: printf("Oops! An invalid choice slipped through. ");
printf("Please try again.\n");
}
choice = menu(); /* get user's subsequent selections */
}
printf("Bye bye!\n");
return 0;
}
int menu(void)
{
int option;
printf("Text Encoder Service\n\n");
printf("1.\tEnter name of input file (currently 'Secret.txt')\n");
printf("2.\tEnter name of output file (currently not set)\n");
printf("3.\tEnter number of characters data should be shifted (currently +7)\n");
printf("4.\tEncode the text\n\n");
printf("0.\tQuit\n\n");
printf("Make your selection: ");
while( (scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 4)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n\n");
printf("Your choice? ");
}
return option;
}
int input()
{
}
int output()
{
return 2;
}
int shift()
{
return 3;
}
int encode()
{
return 4;
}
void quit()
{
printf("Quiting...Bye!");
exit(0);
}
You shouldn't use gets(user_filename) to get the file name since gets() reads up to a \n and stops reading. Your scanf for the menu option does not read the \n at the end of the line when the user types in the menu option. Essentially, you're making gets read a string without words in it. The line you want to read is actually the next line. Using scanf instead of gets will fix it.
Otherwise, your program is working as expected - it's just that your functions don't do anything yet that your menu is "overwriting" the submenus. See http://ideone.com/F2pEs for an implementation with scanf instead of gets.
use getchar(); soon after the gets(user_filename); it will wait to get the character
gets(user_filename);
getchar();
break;
As in this question which Stackoverflow has highlighted as a match, you need to clear out the buffer to remove the newline that's waiting in there.
Add this code after reading a valid menu option:
do
{
c = getchar();
} while (c != EOF && c != '\n');
where c is a char declared up by option. This loops over remaining characters in the input stream until EOF (End Of File) or a newline character is reached, meaning they don't affect your call to gets(). Note that gets() is considered insecure because it doesn't protect against buffer overflow, a user could easily enter more than 100 characters (inc. newline) and start writing into memory that shouldn't be touched by their input. You would do well to lookup the secure equivalent when you see compiler warnings around function calls like this, typically they take a second parameter which is the maximum size of the buffer being read into.
Well, this answer is way late but having come across it, I can't help but write something.
Let's get straight to it. You will have an array of menus, with the array elements being the options you want in your menu. Then while in a truthy condition, loop through the elements of the array, selecting the option you want.
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
//function prototypes
int input();
int output();
int shift();
int encode();
void quit();
int main(){
int menus_on = 1;
const char *menus[5] = {"Input","Output","Shift","Encode","Quit"};
while(menus_on){
int menu,*temp;
for(int i =0;i<6;i++){
printf("%d: %s\n",i,menus[i]);
}
printf("Select menu\n");
scanf("%d",temp);
menu = *temp;
printf("Selected menu::%d\n",menu);
switch(menu){
case 0:
input();
break;
case 1:
output();
break;
case 2:
shift();
break;
case 3:
encode();
break;
case 4:
quit();
break;
default:
printf("Invalid selection\n");
break;
}
}
return 0;
}
int input() {
return 0;
}
int encode () {
return 0;
}

Resources