I'm currently learning C and I'm trying to create a program where the program checks whether a user inputs a letter or an integer:
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[256];
printf("\n Please enter a number or a letter: ");
scanf("%s", &a);
if (isdigit(a[256]) == 1)
{
printf("\n %c is a number.", a);
printf("\n The return value is %d.", isdigit(a[256]));
}
else if (isdigit(a[256]) == 0)
{
printf("\n %c is a letter.", a);
printf("\n The return value is %d.", isdigit(a[256]));
}
getch();
return 0;
}
However, when I run the program, this is what I get:
Please enter a number or a letter: 15
15 is a letter.
The return value is 0.
Or this:
Please enter a number or a letter: X
X is a letter.
The return value is 0.
Any input I type always return the same output. I wanted to pass an array of char so that the program will take in the entire input (e.g. If I input "230", the program will not just check "2" but "230").
Mis-match type (save time, enable all warnings), no width limit, wrong index, wrong compare (is...() return values: Only 0, not 0 important.), wrong function (use isalpha() to test for letter), wrong range passed. (is...() expect EOF,0-255, not char, which may be -128-127)
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[256];
printf("\n Please enter a number or a letter: ");
// scanf("%s", &a);
scanf("%255s", a); // limit input, use matching type
// if (isdigit(a[256]) == 1)
if (isdigit((unsigned char) a[0]))
{
// printf("\n %c is a number.", a);
printf("\n First character %c is a digit.", a[0]);
// printf("\n The return value is %d.", isdigit(a[256]));
printf("\n The return value is %d.", isdigit((unsigned char)a[0]));
}
// else if (isdigit(a[256]) == 0)
else if (isalpha((unsigned char)a[0]))
{
// printf("\n %c is a letter.", a);
printf("\n First character %c is a letter.", a[0]);
// printf("\n The return value is %d.", isdigit(a[256]));
printf("\n The return value is %d.", isdigit((unsigned char)a[0]));
}
else
{
printf("\n Neither digit nor letter.");
}
getch();
return 0;
}
Related
i tried to make a calculator but could the compiler is checking my if conditions properly.
here is my code,
i could not figure out how to solve this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("to add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c",&mode);
printf("%d %d %s \n",first,sec,mode);
if (mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == "s")
{
printf("%d \n",first-sec);
}
else if (mode == "m")
{
printf("%d \n",first*sec);
}
else if (mode == "d")
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
void def(char name[],int age)
{
printf("het ur a %s and yo age is %i \n",name,age);
}
first attempt tried using a string instead of character (failed )
second attempt tried using a character but failed though!!
For comparing a single character in c, you must use single quotes. Consider an array of characters array[4] = {'c','a','r','\0'};
if(array[0] == 'c'){
//...
}
Comparing with double quotes, make the value inside it a string. For comparing strings you should #include <strings.h> and use the strcmp function.
There are two problems
mode == "s" mode is a char so just use mode == 's' and do the same for others also.
printf("%d %d %s \n",first,sec,mode); should be printf("%d %d %c \n",first,sec,mode);
you are using %s for printing a char
In your code "s" is a string not a caracter,to get a caracter you should write like this: 's'
here is the correction of your code :
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("\nMenu : \n");
printf("\nto add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c", &mode);
printf("%d %d %c \n",first,sec,mode);
if(mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == 's')
{
printf("%d \n",first-sec);
}
else if (mode == 'm')
{
printf("%d \n",first*sec);
}
else if (mode == 'd')
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
Every time I run the program, the last "if" statement is not working, it means if I type "no", the loop won't break. Can someone please help me here?
#include <stdio.h>
int main() {
int age, i;
char ans;
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n continue?");
scanf(" %c", &ans);
if (ans == 'no') { // <-- here
break;
} else {
continue;
}
}
return 0;
}
use if (ans == 'n'). If you want to use the word "no", you have to change the type of variable ans to char array and use strcmp() method to compare strings.
In c programming single quotes (i.e. 'c') are used for characters and double quotes (i.e. "c") are used for strings. In double quotes last character is NULL.
Note: We cannot keep two characters in single quote like 'no'.
In your case first thing, declare ans as character array(i.e. string).
char ans[SIZE_AS_PER_REQUIREMENT];
To take input in this,
scanf("%s",ans);
For a better user experience before taking input give a proper message to user.
printf("\n Do you want to continue(yes/no)?");
Now to compare user's answer with program's condition, We have C-Language string library (i.e. string.h), include this before using any C-language inbuilt String function.
#include <string.h>
and use any of string function strcmp or stricmp as per requirement. Here I am going to use stricmp because it is possible that user may enter "no"/"No"/"NO". stricmp ignore the case.
stricmp(string1,string2)
It returns
Negative Number if string1 is less than string2
Zero if string1 equivalent to string2
Positive Number if string1 is greater than string2
So, for our case we check for Zero.
See the below program, I just added these in your code.
#include <stdio.h>
#include <string.h>
int main() {
int age, i;
char ans[5];//declare ans as character array
for (i = 0; i < 3; i++) {
printf("\n enter your age:");
scanf("%d", &age);
if (age > 18) {
printf("your age is %d, you are allowed to enter", age);
} else if (age == 18) {
printf("I don't know what to do with you");
} else {
printf("your age is %d, you are not allowed to go in", age);
}
printf("\n Do you want to continue(yes/no)?");
scanf("%s",ans);//take input as string in ans, its character array
if (stricmp(ans,"no") == 0) { // 0 means both are equal
break;
} else {
continue;
}
}
return 0;
}
You used %c which is for characters.
Instead, use %s.
The problem is, basically, that if user enters a:5, b:f, everything works fine. But if it's the other way around and enters a letter to the 'a' variable, the program ends saying "Incorrect input", not letting the user to finish typing in rest of the variables. Why? Is it because of how I dealt with checking if the input is correct in the first place? How to "delay" the message and make it show after user finishes entering variables?
Here's the code:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
As Weather Vane already pointed out, the reason the program exits is, that when you enter a character (%c) and the scanf function is waiting for a integer (%d) it ignores the char, doesn't find an int but ends its' search on the '\n' (enter), so your variable l1 stays 0. This happens for all of your scanf calls, as it doesn't clear the buffer from characters that don't match.
Solving this
You can clear the input buffer, so that all the other scanf calls can get an actual input, though, you are still going to get an "Incorrect input" at the end.
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
printf("Number b: ");
l2 = scanf("%d", &b);
while (getchar() != '\n');
If you want to repeat the input process until a user enters the numbers correctly, you have to check the return value of the scanf in a while loop, something like this:
do {
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
} while (l1 != 1 || l1 != EOF);
Try this:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
getchar();
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
Reference : scanf() leaves the new line char in the buffer
When I'm trying to run without debugging the code everything runs smooth but as soon as I press Y so I can continue inputting numbers it terminates (gotta say I need help)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
The character read by getchar() is the pending newline that was typed after the number but was not consumed by scanf_s.
You should consume this pending newline before reading the next character for the continuation test, which can be done easily in scanf with a space before the %c conversion specification:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}
I want to run this code where I enter two strings and user put the option for performing the following task.
After I enter 'a' in the menu, the statement strcpy(s_1,s_2); the string is copied to s_1 but when I added
#include <string.h>
it asked me to use strcpy_s() which I did and code stopped working.
When I enter 'b' in the menu, I get only one output
Both Strings are equal to each other
I don't understand why strcmp() returns 0 always.
It would be great if someone help me out in this issue.
By the way I'm using Visual Studio 2015 for compiling my C code.
#include< stdio.h>
#include< string.h>
#include< stdlib.h>
#include< process.h>
//USER-DEFINED FUNCTIONS
char top_down();
char copy_function();
char compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header()
{
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
main()
{
//VARIABLE DECLARATION
char x =
{ 0 };
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
//TERMINAL-PAUSE
system("pause");
}
char top_down()
{
char s1[MAX] =
{ 0 }, s2[MAX] =
{ 0 }, x =
{ 0 };
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf_s("%c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x)
{
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s1);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
return;
}
}
char copy_function(char s_1[], char s_2[])
{
int x = 0;
x = strlen(s_2);
printf("Second String will be copied to First string now \n");
//strcpy(s_1, s_2);
strcpy_s(s_1, x, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
return;
}
char compare_function(char s_1[], char s_2[])
{
int a = 0, l1 = 0, l2 = 0, i = 0;
printf("First String will be compared to Second String now \n ");
//printf("\n");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
return;
}
Not sure if your program is in progress. I modified it and removed anything I thought was not necessary.
The functions' signatures change to void
Removed x in main
Return type of main set to int (It is int by default, but this spares you the warning of the compiler)
I work on Linux, so I removed the system(...), feel free to add it.
Only left variables declarations in top_down (not important, but an initial value should have a meaning and in your case there is no meaning to 0)
Changed scanf_s("%c", &x); to scanf(" %c", &x); (note the space. not sure if on windows that makes a difference. please check.)
Changed the function call compare_function(s1, s1); to compare_function(s1, s2);
Removed the return statements in the void functions
In copy_function I removed int x = 0; and x = strlen(s_2);
In copy_function I changed strcpy_s(s_1, x, s_2); to strcpy(s_1, s_2);
In compare_function I removed int a = 0, l1 = 0, l2 = 0, i = 0;
You use label/goto. That's ok, but considered not cool nowadays. You could use a loop and break in case of an invalid option.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//USER-DEFINED FUNCTIONS
void top_down();
void copy_function();
void compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header() {
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
int main() {
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
return 0;
}
void top_down() {
char s1[MAX], s2[MAX], x;
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf(" %c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x) {
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s2);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
}
}
void copy_function(char s_1[], char s_2[]) {
printf("Second String will be copied to First string now \n");
strcpy(s_1, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
}
void compare_function(char s_1[], char s_2[]) {
printf("First String will be compared to Second String now \n ");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
}