Check if the number is even or odd - c

My program gives me error(not exactly an error but it just prints error instead of even or odd) even if I put a number or letters. The code works if I remove the isdigit checker(3rd line). I do no know what am I doing wrong. Can someone please help me. Thanks in advance. Here is my code.
int main()
{
int n;
printf("Input an integer\n");
scanf("%d", &n);
if(!isdigit(n))
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}

isdigit is not for this purpose.
If you want to check if the input is vaild, one method is to load with %s and use strtol.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void print(const char *s) {
puts(s);
}
int main()
{
char nstr[100] = {0};
int n;
char *e;
printf("Input an integer\n");
scanf("%99s", nstr);
n=(int)strtol(nstr, &e, 10);
if(nstr[0] == '\0' || *e != '\0')
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}

man -a isdigit
isdigit()
checks for a digit (0 through 9).
Thus isdigit fails if ascii value of n is not anything but
Oct Dec Hex Char
--------------------------
060 48 30 0
061 49 31 1
062 50 32 2
063 51 33 3
064 52 34 4
065 53 35 5
066 54 36 6
067 55 37 7
070 56 38 8
071 57 39 9
man -a ascii
thus,
if(!isdigit(n))
{
print("error");
return 0;
}
is not an appropriate option. you should probably find some other option to validate n.

The isdigit function checks a character to see if it is in the '0' to '9' range. More specifically, it checks if the ASCII value of the character is between 48 (the code for '0') and 57 (the code for '9').
You're passing an int to this function, not a character, so it's not appropriate to use this function here. Just remove this check and it will work.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Please enter your number\n");
scanf("%d",&n);
if( n%2==0)
printf("The number is even\n");
else
printf("The number is odd\n");
System("pause");
return 0;
}
Check this one.

Related

How to input stdin strings into array and print them? C Programming

I am practicing how to code C programs, specifically reading stdin statements. The following is a code I wrote to take in the stdin, but I am having trouble inputting them into an array and printing out the correct values.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int count = 0;
char* number = "-n";
int result;
char numArray[50];
result = strcmp(argv[1], number);
if (result == 0) {
printf("Numbers Only\n");
while (!feof(stdin)) {
if (feof(stdin))
break;
for (int i=0; i < sizeof(numArray); i++){
scanf("%s", &numArray[i]);
}
}
}
for (int i=0; i< sizeof(numArray); i++){
printf("%d\n", numArray[i]);
}
}
I am working step by step, so my final code has something to do with manipulating the array and outputting it. However, my question is focusing solely on inputting the stdin into the array first since that is the big step and I will work on manipulating the array later.
The 'Numbers Only' is what I was using to check something out, so do not worry about that at all.
I do not get any errors for the code, but it gives weird outputs. One output is the following:
1 (1, 2, 3 are what I inputted into terminal)
2
3
49
50
51
0
0
0
0
0
32
-56
109
-63
6
127
0
0
-128
80
110
-63
6
127
0
0
20
0
0
0
0
0
0
0
64
0
0
0
0
0
0
0
0
0
-16
-67
6
127
0
0
4
0
Can anyone explain why it outputs those other numbers when my stdin stops after I input 1 2 3 ctrl+D and how I can stop that from happening? I want my array to be the size of how many numbers I input, but I am also having trouble with that if anyone has hints!
Thanks!
The innermost loop is not necessary, only one loop is enough.
When converting with scanf, check its return value.
Also, only print the number of elements actually converted.
Fixing these, a first corrected version is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[])
{
int count = 0;
char* number = "-n";
int result;
int numArray[50];
int i = 0;
if (argc != 2)
return EXIT_FAILURE;
result = strcmp(argv[1], number);
if (result == 0) {
printf("Numbers Only\n");
while (1) {
int number = 0;
int ret = scanf("%d", &number);
if (ret == 1)
numArray[i++] = number;
if (i == 50 || ret < 1)
break;
}
}
for (int j=0; j< i; j++){
printf("%d\n", numArray[j]);
}
}
Testing:
$ gcc main.c && ./a.out -n
Numbers Only
1
2
3
<CTRL + d here>
1
2
3
Edits from comments: Removed while (!feof(stdin)), expanded error checking to avoid infinite loop and added a check before accessing argv.

How to print ASCII codes for letters?

How do I create a program where the input of a letter (a-z) is converted to ASCII and printed out. I am stuck at the point where it has to show all the ASCII numbers before it.
Let's say if the user inputs the character c, I want to print out 97,98,99 for character inputs a,b,c respectively.
I am somewhat a beginner. Pretty sure I have to use a loop.
Hi, as I am a beginner can you possibly check my way of doing it, unsure where I am doing wrong. Your code has a few things which I am unfamiliar with. I am aiming to restrict it to only A-Z. So here's the code :
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
for (c=65;c<91;c++)
{
if(c==z)
printf("%c",z);
}
return 0;
}
#include <stdio.h>
void get_ASCII_value(char c)
{
printf("The ASCII value of %c = %d", c, c);
}
int main(void)
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
get_ASCII_value(c);
return 0;
}
To clarify, %d prints the ASCII value for that specific char
As for your specific case:
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
if (z < 65 || z > 90)
return 0;
for (c = 65; c <= z; c++)
printf("The ASCII value of %c = %d\n", c, c);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void)
{
for(uint8_t c = 0; c < UCHAR_MAX; ++c)
{
uint8_t out[2] = {c};
printf("%d (%s)\n", c, isprint(c)? out : "*unprintable*");
}
return 0;
}
###Output
Success #stdin #stdout 0s 4288KB
0 (*unprintable*)
1 (*unprintable*)
2 (*unprintable*)
3 (*unprintable*)
4 (*unprintable*)
5 (*unprintable*)
[....]
29 (*unprintable*)
30 (*unprintable*)
31 (*unprintable*)
32 ( )
33 (!)
34 (")
35 (#)
36 ($)
37 (%)
38 (&)
39 (')
40 (()
41 ())
42 (*)
43 (+)
[...]
65 (A)
66 (B)
67 (C)
68 (D)
69 (E)
70 (F)
71 (G)

How i take hex input into array from users c

I will take hex input from user into buffer array, but i don't take it, scanf does not appropriate. Input data like this (0x 06 41 42 43 0f 52 53). Also then i want to transform string to integer type some part of array. I used atoi, what is best way for it?
#include <stdio.h>
int main(){
char buffer[1000];
char dest[3];
int x;
//scanf("%s",buffer);
x=atoi(strncpy(dest,buffer+1,4))
}
The following simple function converts a string with a hexadecimal number to an integer:
int atox(const char *s)
{
int x= 0;
while (*s) {
x= x*16+(*s>'9'?(toupper(*s)-'A'+10):*s-'0');
s++;
}
return x;
}
and call it like:
printf("%02x\n",atox("42"));
printf("%02x\n",atox("a1"));
printf("%02x\n",atox("A1"));
Note that the string must be exactly the string to convert, so no spaces or whatever.
Here is the code using strtol function considering numbers as Hex inside the string (For base value 8 they will be octal):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s="00 06 41 42 43 0f 52 53";
char *endpoint=s;
int base=16,count=1;
long int result=0;
do
{
result=strtol(endpoint,&endpoint,base);
printf("value %d %ld\n",count,result);
count++;
}while((endpoint - s) < (size_t)strlen(s) );
return 0;
}

i'm not processing more than one block correctly

I have an assignment where I'm suppose to read input lines such as
2
67 5 100 1 11 97 98 10 1 110
15 72 10 101 47 67 88 20 94 6 22 11
4
61 11 93 4 73 39 78 34 17 104
23 43 11 93 65 52 20 96 66 31 86 24 40 61 102 13 50 51
73 43 28 73 8 89 31 68 77 27 24 77 42 72 15 24 64 51
25 75 7 90 10 111 17 16
.....
process every two integers (the first line in a block only tells us how many words we will process), add them then match
them to their corresponding ASCII char. The example above would be two blocks.
The output should be:
Decoded messages:
Hello World!
Happy Bhutanese teacher's day!
I'm having problems when it comes to dealing with a file with multiple blocks, more than 20 and so forth following the same format on one input text. I can handle one block fine, two blocks okay but not fine because my program doesn't seem to end. No line will be longer than 256 characters. numOfPuzzl refers to how many words we process per block.
I'd greatly appreciate any help. I attached my code and commented as much as I can too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
//user will type in file name they choose to process and we allocated in filename[]
char filename[256];
printf("Enter filename: ");
scanf("%s", filename);
//process filename username typed in
FILE *pFile;
pFile = fopen(filename, "r");
//if there's nothong to read
if (pFile == NULL){
exit(1);
}
printf("Decoded messages:\n");
//create array we will putting lines into
char myString[256];
//simply gets the first line, which is always a lone integer
fgets(myString, 256, pFile);
int numOfPuzzl;
sscanf(myString, "%d", &numOfPuzzl);
//printf("puzzles to solve: %d\n", numOfPuzzl);
int wordsProcessed = 0;
//just remember that myString has entire line
//start processing the lines that follow, a line is a word
while (fgets(myString, 256, pFile) != NULL){
int num = 0; //first integer in line
int secondNum = 0; //second int. in line
int tot = 0; //how many bytes
int bytes_read = 0; //bytes processed
char *endOfStrAdr = strchr(myString, '\0'); //returns address of end terminating char.
int endOfStrIdx = endOfStrAdr - myString; //this will give me the index of where the terminating char. occurs within my array
//start scanning integers within array making sure to not sccan out of bounds
while (tot < endOfStrIdx){
//first integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &num, &bytes_read);
tot += bytes_read; //keeps tab so we don't have to read from the begn. of array everytime
//second integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &secondNum, &bytes_read);
tot += bytes_read; ////keeps tab so we don't have to read from the begn. of array everytime
printf("%c", (char) num + secondNum); //add the two integers and cast them to char
//we want to check if we are the end of the string, our word
if (tot == endOfStrIdx){
printf(" ");
wordsProcessed++;
//we want to print a new line char. if we finished processing all the words for the puzzle
if (wordsProcessed == numOfPuzzl){
printf("\n");
fgets(myString, 256, pFile);
}
}
}
}
fclose(pFile);
}
Ignore blank lines between puzzles.
Reset parameters (numOfPuzzl and wordsProcessed) before processing new puzzles.
To archive that, change
if (wordsProcessed == numOfPuzzl) {
printf("\n");
fgets(myString, 256, pFile);
}
into
if (wordsProcessed == numOfPuzzl) {
printf("\n");
while ( fgets(myString, 256, pFile) != NULL ){
if ( sscanf(myString, "%d", &numOfPuzzl) == 1 )
break;
}
wordsProcessed = 0;
}
I suggest like this:
#include <stdio.h>
#include <stdlib.h>
//stringize macro
#define S_(x) #x
#define S(x) S_(x)
int main(void){
char filename[FILENAME_MAX + 1];
printf("Enter filename: ");
scanf("%" S(FILENAME_MAX) "[^\n]", filename);
FILE *pFile;
if(NULL==(pFile = fopen(filename, "r"))){
perror("can't opne file");
exit(EXIT_FAILURE);
}
printf("Decoded messages:\n");
int numOfLines;
while(1==fscanf(pFile, "%d", &numOfLines)){
for(int i = 0; i < numOfLines; ++i){
int num1, num2, state;
char ck;
while(3==(state=fscanf(pFile, "%d %d%c", &num1, &num2, &ck)) || 2 == state){
putchar(num1 + num2);
if(state == 2 || state == 3 && ck == '\n')
break;
}
putchar(' ');
}
putchar('\n');
}
fclose(pFile);
return 0;
}

Program is removing spaces in string uninteded

I am a beginner programmer taking a class and I cannot get my output strings to print with spaces in between words. Here is my code below. It is supposed to take a string that I input and either change to all caps or all lower case as I specify when I run the program. If I put in MY CODE DOES NOT WORK, it outputs mycodedoesnotwork. Why is it removing the spaces?
1 #include <stdio.h>
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6
7 int shout(char * msgIn, char * msgOut) {
8
9 if (!msgIn || !msgOut)
10 return -1;
11 while (*msgIn != '\0') {
12 if ('a' <= *msgIn && *msgIn <= 'z')
13 *msgOut = *msgIn + ('A' - 'a');
14 else
15 *msgOut = *msgIn;
16 msgIn++;
17 msgOut++;
18 }
19 *msgOut = '\0';
20
21 return 0;
22 }
23
24
25 int whisper(char const * msgIn, char * msgOut) {
26 if (!msgIn || !msgOut)
27 return -1;
28 while (*msgIn != '\0') {
29 if ('A' <= *msgIn && *msgIn <= 'Z')
30 *msgOut = *msgIn + ('a' - 'A');
31 else
32 *msgOut = *msgIn;
33 msgIn++;
34 msgOut++;
35 }
36 *msgOut = '\0';
37 return 0;
38 }
39
40 int main(int argc, char ** argv) {
41 char in[128], out[128];
42 int i;
43 for (i = 1; i < argc; i++) {
44 if (strcmp("-w", argv[i]) == 0)
45 while (scanf("%s", in) != EOF) {
46 whisper(in, out);
47 printf("%s", out);
48 }
49 else if (strcmp("-s", argv[i]) == 0)
50 while (scanf("%s", in) != EOF) {
51 shout(in, out);
52 printf("%s", out);
53 }
54 }
55 printf("\n");
56 return 0;
57 }
~
~
The scanf calls are reading in just the words (no spaces) and you are not adding spaces back in when you output your strings.
If you don't mind a trailing space, just change lines 47 and 52 to printf("%s ", out)
while (scanf("%s", in) != EOF)==> scanf() takes input up to space and send to function
and then in next iteration again takes word after space.
You need to use fgets() instead.
It is not problem with your shout() or wisper() functions, but problem with scanf().
When you specify %s to read string, the string will terminate at any white space chars - space, tab etc.
And that will not be included in the string. So space that you enter between the strings are not stored in in variable.
You may want to think of different approach to solve that.
The space is a string terminator for scanf() and scanf() does not include it in the acquired string. man 3 scanf

Resources