Reputation: 394
I'm trying to check if all the upper-case letters are present in the input the user entered.
I tried to make an array of 26 values, 0 will represent A and 25 is Z. At first I initialize the values to 0.
After that I asked the user for input and then I checked if it matches with the ASCII. If yes, I changed the array value to 1.
After that, I make sure all the array values are 1; if yes all the letters were in the input.
I assume that the user will end the input with 0.
The input is "THE Q$@UICK BROWN FOX JUMPS OVER tHe LAZY DOG!0".
This is the code:
#include <stdio.h>
int main()
{
int z;
int x = 1;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
z=0;
while (arr[z]==1 && z<26) {
++z;
if (z==26) {
printf("all the ABC in ur sentance\n");
break;
}
}
printf("all the ABC does not in ur sentance\n");
return 0;
}
There is no output and I think it's because there is a problem with the scanf, but I don't know how to solve it.
Upvotes: 1
Views: 63
Reputation: 75062
%d
format specifier in scanf()
is for reading integers, not characters. In this case, you should use getchar()
instead of scanf()
to read characters one-by-one.0
don't have the value 0. (it is 48 in ASCII).65
is not good. Using character constants like 'A'
should be good in this case to make the meaning clear.The part
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
should be:
while ((x = getchar()) != '0' && x != EOF) {
z = x - 'A';
if (z>=0 && z<=25) {
arr[z]=1;
}
}
Also note that "all the ABC does not in ur sentance\n"
will be printed even after "all the ABC in ur sentance\n"
is printed. You should use return 0;
instead of break;
to finish the execution of the function and prevent the extra string from being outputted.
Upvotes: 4
Reputation: 780673
You need to use %c
to read a character and convert it to its character code. %d
reads the representation of an integer.
If the character 0
ends the input, you need to compare with '0'
, not 0
.
You can use isupper()
to test if a character is an uppercase letter, rather than testing the range yourself.
The loop to check that all the characters have been entered can be simplified as I've shown below.
#include <stdio.h>
#include <ctype.h>
int main()
{
int z;
char x;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (1) {
scanf(" %c", &x);
if (x == '0') {
break;
}
if (isupper(x)) {
z = x - 'A';
arr[z]=1;
}
}
for (z = 0; z < 26; z++) {
if (arr[z] == 0) {
printf("all the ABC are not in your sentance\n");
return 0;
}
}
printf("all the ABC in your sentance\n");
return 0;
}
Upvotes: 3