Testing to see if a string only contains alphabetic numbers - c

I am studying C but am stuck on a program I've been trying to create. Essentially I'm testing to see if a character string only contains alphabetic characters a-z or A-Z.
What I have done:
defined a function called strisalpha to do this
called the function in my "test bench", which asks the user to enter a string
What goes wrong in the gcc compiler:
testBench1.c:21:28: warning: implicit declaration of function 'atoi' [-Wimplicit-function-declaration]
integerCharValue = atoi( string[loopPointer1] );
This is my definition of strisalpha:
int strisalpha(char *string)
{
int stringLength = 0;
int loopPointer1 = 0;
int integerCharValue = 0;
int dummyArgument = 0;
/* Get length of string */
stringLength = strlen (string);
printf("\nString length is: %d", stringLength);
/* ASCII Codes In Decimal */
A (65Decimal) to Z(90Decimal) and
a (97Decimal) to z (122Decimal)
Set up a loop and query if ASCII alphabetic character
*/
for (loopPointer1 = 1; loopPointer1 > stringLength; loopPointer1++ )
{
/* Convert character to integer */
integerCharValue = atoi( string[loopPointer1] );
printf ("%d \n", integerCharValue);
if (integerCharValue >= 65)
if (integerCharValue <= 90)
return 1; /* Upper case alphabetic character, so OK */
else if (integerCharValue >= 97)
if (integerCharValue <= 122)
return 1; /* Lower case alphabetic character, so OK */
else
The result always says I entered an ASCII character, even if I didn't. Please could someone shed some light on what I'm doing wrong? Thanks

The main problem is your for loop
for (loopPointer1 = 1; loopPointer1 > stringLength; loopPointer1++ )
Arrays in C start at 0 and the middle section defines if the loop should continue not finish. So what you want is:
for (loopPointer1 = 0; loopPointer1 < stringLength; loopPointer1++ )
And then for checking each character you don't need to do anything to them as you can compare characters like this for example
if (string[loopPointer] >= 'A')

atoi isn't what you want to use here. chars are already stored as numeric ASCII values. You can just set integerCharValue = string[loopPointer1].
Your loopPointer1 is starting at 1, so you will skip the first character in the string. In C, the index starts at 0.
Also, you don't want to return immediately if you find a letter. Calling return will exit the function and stop your loop. What you probably want to do is look for characters that are not letters, and return 0 if you find one. Then, if you make it to the end of the loop, you can return 1 because you know you didn't find any characters that weren't letters.

Here is a one-liner function that evaluates to 1 if the string only contains alphabetic characters, and 0 otherwise:
#include <string.h>
int strisalpha(const char *str) {
return str[strspn(str, "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ")] == '\0';
}
And here is a more classic approach with isalpha():
#include <ctype.h>
int strisalpha(const char *str) {
while (*str) {
if (!isalpha((unsigned char)*str++)
return 0;
}
return 1;
}

Related

In C, How can I check an array for only ASCII defined Letters Without using tons of If Statements?

I'm trying to make sure that the array entered at the command line is only letters, Capital and lowercase.
If it is numbers or anything else then I want to end the program.
Now, I know I can do this with tons of if statements to see:
if it is between this and that
else this and that
else this and that.
But I would like to try and learn a more efficient way to do this because I'm sure there is one with a for loop I just havent figured it out. I ask because I want the user to enter a key that is x amount long. And to achieve the desired / required string length I used a similar method of multiple if else statements.
#include <stdio.h>
#include <string.h>
int validate_key(int argc, string argv[]);
int main(int argc, string argv[])
{
string input;
int score;
score = validate_key(argc, argv);
if (score == 0)
{
// if required key is valid, next function of program here
}
}
int validate_key(int argc, string argv[])
{
//KEY VALIDATION
int l = 0; //initialize length variable
string s;
//To make sure that the string entered at command line is the required 26 characters,
//and that it isnt empty
if (argc == 2) //make sure there are no spaces in the entered string
{
s = argv[1]; //assign key to string s
l = strlen(s); //check length of KEY
}
//check to see string isnt NULL / empty
if (argc !=0 && l == 26)
{
//make a for loop that scans the array making sure it is between two values?
//attempting to check argv to make sure it is a lowercase and or uppercase string
for (int i = 0; i < l; i++)
{
int charValue = argv[1][i];
if ( ( charValue > 64 && charValue < 91 ) || ( charValue > 96 && charValue < 123 ) )
{
printf("%c\n", charValue); //to show me that it made it into the if statement
}
else
return 1;
}
return 0;
}
else if (l <= 25 && l >= 1) //entered key is too small
{
printf("Please Enter 26 Letter Key \n");
printf("value of l: %d\n", l);
return 1;
}
else //entered key is empty
{
//printf("value of l: %d\n", l);
printf("missing command-line argument\n");
return 1;
}
}
Use isalpha():
7.4.1.2 The isalpha function
Synopsis
#include <ctype.h>
int isalpha(int c);
Description
The isalpha function tests for any character for which isupper or
islower is true, or any character that is one of a locale-specific set
of alphabetic characters for which none of iscntrl, isdigit, ispunct,
or isspace is true.200) In the "C" locale, isalpha returns true only
for the characters for which isupper or islower is true.
In your code:
for (int i = 0; i < l; i++)
{
// see notes below regarding the cast
int charValue = ( unsigned char ) argv[1][i];
if ( isalpha( charValue ) )
{
printf("%c\n", charValue); //to show me that it made it into the if statement
}
else
return 1;
}
Note, though, that the value passed must be representable as an unsigned char:
The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.
The basic operation will always be to iterate over the characters in the input string and check whether they are that what you want them to be: uppercase or lowercase letters. There are some functions that make it more convenient for you to code.
To avoid coding the ASCII number ranges yourself, you can use the C standard function isalpha() to check a single character whether it is a letter.
You could also use the strcspn function to find the number of matching characters at the start of your string. Your matching set can be a string with all the ASCII letters. If the returned length is the length of the whole string, there were no other characters in it. If the returned length is less than the length of the string, then there is a non-letter character... This is probably less efficient for the computer because strcspn does not simply check whether the characters are in a range, but whether the characters appear in the matching string.
The particular question was in regard of testing for non-alphabetic characters.
There are already two quality answers referring you to isalpha().
The meta- question is "how can I write less code?"
The following (using isalpha()) is offered as a teaching example that performs the same function as the OP code above. By compacting the code to fewer lines, a reader is able to scan its operation without scrolling. Unused variables such as input and s are quick to find and expunge.
#include <stdio.h>
#include <string.h>
#include <cs50.h> // Missing from OP code
// defining the function ahead of its use. Definition is its own prototype.
int unique26( string arg ) {
int i = 0;
// test all alpha and is exactly 26 chars long
while( isalpha( (unsigned char) arg[i] ) i++;
if( i != 26 || arg[i] )
return 0; // bad
// test no duplications in the sample
for( i = 0; arg[i]; i++ )
for( int j = i + 1; arg[j]; j++ )
if( arg[j] == arg[i] )
return 0; // bad
return 1; // good
}
int main( int argc, string argv[] )
{
if( argc != 2 || !unique26( argv[1] ) )
{
printf( "Usage: %s <key (26 unique alphabetic chars> \n", argv[0] );
return 1;
}
// more code here
return 0;
}
I'd be happy to answer any questions this example code.
EDIT:
To write even less code, the function unique26() could use strchr(), a tested and proven function from what is called "the C string library".
int unique26( string arg ) {
int i = 0;
while( isalpha( (unsigned char) arg[i] ) i++;
if( i != 26 || arg[i] )
return 0; // bad
// test no duplications in the sample
for( i = 1; arg[i] && strchr( &arg[i], arg[i-1] ) == NULL; i++ ) {}
return arg[i] == '\0;
}
It's good to be aware of library functions, even if you may not have use for some... until you do.

The program accepts only letters and prints them backwards

I want the program to accept only upper and lower case letters, and if the user enters any numbers or symbols other than upper and lower case letters, the system will stop accepting characters and output the result backwards. I am use isalpha() on my code.
Here is my code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char users_enter[21]; // set an character variables that include 21 characters
int str_length = 0; // set the length of string is 0
printf("Please print the string: \n");
scanf("%20s",users_enter); // accept character
for(int index = 0; index < 20; index++) { // set the index of elements of string is 0
if(isalpha(users_enter[index]) == 0) { // is character is num will return 0
str_length = strlen(users_enter); // find the length of current string
break; // stop loop
}
}
for(int len = str_length-1; len >= 0; len--) {
printf("%c",users_enter[len]); // print
}
printf("\n");
return 0;
}
The test result is :
Please print the string:
str5y
y5rts
my program did not stop when I enter 5.
The expected result should be rts.
How to modify my code?
Thank you
Instead of getting the length of the whole string, save the current index.
if(isalpha(users_enter[index]) == 0) { // is character is num will return 0
str_length = index; // find the length of current string
break; // stop loop
}
This way when you find an undesired character, you will have the length of the string just before that character.
You could also get input character by character and stop when you encounter a number.
Sidenote:
Check the return value of scanf(), so that you can exit if you encounter a conversion error while getting input.

how to fix this code so that it can test the integers present next to the character?

Given a string containing alphanumeric characters, calculate the sum of all numbers present in the string.
The problem with my code is that it displays the integers present before the characters, but it is not summing up the integers after the characters.
The execution is easy in python and C++ but I cant get it done using C! Can anyone please verify where I have done wrong? << thank you !
enter code here
#include<stdio.h>
#include<string.h>
int convert(char[]);
int main()
{
char ch[100],temp[100]={0};
int i=0,s=0,j=0,n;
scanf("%s",ch);
for(i=0;i<strlen(ch);i++)
{
if((ch[i]>='0') && (ch[i]<='9'))
{
temp[j]=ch[i];
j++;
}
else
{
if(temp[0]== '\0')
{
continue;
}
else
{
n=convert(temp);
s+=n;
temp[0]= '\0';
j=0;
}
}
}
printf("%d",s);
return 0;
}
int convert(char s[]) //converting string to integer
{
int n=0;
for(int i=0;i<strlen(s);i++)
{
n= n * 10 + s[i] - '0';
}
return n;
}
Input : 12abcd4
Expected output : 16
But the output is 12 for my code.
There are two problems in your code. The first was mentioned in the comments : if the last character is a digit, the last "number section" will not be taken into account. But I don't think that the solution given in the comments is good because if the last character is not a digit, you will have a wrong value. To correct this, I added an if statement that check if the last character is a digit, if so call convert().
The second problem is that strlen return the number of characters in you string from the beginning until it finds an '\0'. The way you used your string lead to the follow problem :
ch = "12abcd4".
At first you have temp = '1' + '2' + '\0'...
After calling convert() you set temp[0] to '\0', thus temp = '\0' + '2' + '\0'... .
And when you start reading digit again, you set '4' in temp[0]. Your string is now : '4' + '2' + '\0'... .
The n returned will be 42 and your result 54 (12+42). There are several solution to have the expected behavior, I chose to use your variable j to indicate how many characters should be read instead of using strlen() :
#include<stdio.h>
#include<string.h>
int convert(char[], int size);
int main() {
char ch[100],temp[100]={0};
int i=0,s=0,j=0,n;
scanf("%s",ch);
for(i=0;i<strlen(ch);i++) {
if((ch[i]>='0') && (ch[i]<='9')) {
temp[j]=ch[i];
j++;
// change here
if(i == strlen(ch) - 1) {
n=convert(temp, j);
s+=n;
}
}
else {
// change here
n=convert(temp, j);
s+=n;
if(temp[0]== '\0') {
continue;
}
temp[0]= '\0';
j=0;
}
}
printf("%d\n",s);
return 0;
}
//change here
int convert(char s[], int size) {
int n=0;
for(int i=0;i<size;i++) {
n= n * 10 + s[i] - '0';
}
return n;
}
You could use a combination of strtoul() and strpbrk() to do this.
Declare two character pointers start_ptr and end_ptr and make start_ptr point to the beginning of the string under consideration.
char *start_ptr=s, *end_ptr;
where s is the character array of size 100 holding the string.
Since your string has only alphanumeric characters, there is no - sign and hence there are no negative numbers. So we can get away with using unsigned integers.
We are using strtoul() from stdlib.h to perform the string to integer conversion. So let's declare two variables: rv for holding the value returned by strtoul() and sum to hold the sum of numbers.
unsigned long rv, sum_val=0;
Now use a loop:
for(; start_ptr!=NULL; )
{
rv = strtoul(start_ptr, &end_ptr, 10);
if(rv==ULONG_MAX && errno==ERANGE)
{
//out of range!
printf("\nOut of range.");
break;
}
else
{
printf("\n%lu", rv);
sum_val += rv;
start_ptr=strpbrk(end_ptr, "0123456789");
}
}
strtoul() will convert as much part of the string as possible and then make end_ptr point to the first character of the part of the string that could not be converted.
It will return ULONG_MAX if the number is too big and errno would be set to ERANGE.
Otherwise the converted number is returned.
strpbrk() would search for a set of characters (in this case the characters 0-9) and return a pointer to the first match. Otherwise NULL is returned.
Don't forget to include the following header files:
stdlib.h ---> strtoul
string.h ---> strpbrk
limits.h ---> ULONG_MAX
errno.h ---> errno
In short, we could make the program to something like
for(; start_ptr!=NULL; sum_val += rv, start_ptr=strpbrk(end_ptr, "0123456789"))
{
rv = strtoul(start_ptr, &end_ptr, 10);
if(rv==ULONG_MAX && errno==ERANGE)
{
//out of range!
break;
}
}
printf("\n\n%lu", sum_val);
So the value of sum_val for the string "12abcd4" would be 16.
scanf() is usually not the best way to accept input that is not well-formatted. Maybe you can use fgets()-sscanf() combo instead.
If you must use scanf(), make sure that you check the value returned by it, which in your case must be 1 (the number of successful assignments that scanf() made).
And to prevent overflow, use a width specifier as in
scanf("%99s",ch);
instead of
scanf("%s",ch);
as 100 is the size of the ch character array and we need one extra byte to store the string delimiter (the \0 character).

C language - counting number of different vowels with no pointers or additional functions

I got this exercise that I haven't been able to solve, the point is to create a program where you type in a text, then the program analyzes each word of the text and counts the vowels of each word, then the program returns in screen the number of words that have 3 or more different vowels, and by different I mean, it doesn't matter if the word has 3 "a", it only count as one (the word has the vowels "a", it doesn't matter how many times), so for example, the word "above" has 3 vowels, the word "been" has 1 vowels, the word "example" has 2 vowels. The vowels can be upper case or lower case, it doesn't matter, and here is the tricky part: It cannot contain any pointers or functions made by us.
what i did was asking the user to enter word by word so the program analyze each word, and then at the end returns the number of words that contain 3 or more vowels, but I feel like there must be an easier way where the user can type a complete paragraph or text, then the program analyzes each word and return the number of words that have 3 or more different vowels.
Anyway, my code is as follows, any suggestions would be appreciated:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
main() {
int vowels, text, words, c, total=0,a=0,e=0,i=0,o=0,u=0;
printf ("How many words does your text has? ");
scanf("%d",&words);
for(c=1;c<=words;c++){
printf("Type your word %d, after that press enter, then press 'control' and 'z' at the same time, and then press enter again: \n", c);
while (EOF != (text=getchar())){
if (text == 'a' || text == 'A'){
a++;
if (a >=2){
a = 1;
}
}
if (text == 'e' || text == 'E'){
e++;
if (e >=2){
e = 1;
}
}
if (text == 'i' || text == 'I'){
i++;
if (i >=2){
i = 1;
}
}
if (text == 'o' || text == 'O'){
o++;
if (o >=2){
o = 1;
}
}
if (text == 'u' || text == 'U'){
u++;
if (u >=2){
u = 1;
}
}
}
vowels = a+e+i+o+u;
if(vowels >=3){
total = total +1;
}
a=0,e=0,i=0,o=0,u=0;
vowels = 0;
}
printf("\n\nThe total of words with 3 or more vowels is: %d", total);
printf("\n");
total=0;
return 0;
}
In order to read and analyze a single word, or a paragraph words to determine the number of words that contain at least three different vowels (of any case), this is one of the rare times when reading input with scanf (using the '%s' format specifier) actually is a reasonable choice.
Recall the '%s' format specifier will read characters up to the first whitespace. That gives you a simple way to read a word at a time from stdin. To end input, the user simply need to generate an EOF by entering ctrl+d (or ctrl+z on windows). This satisfies your paragraph requirement.
For parsing, you can take advantage of converting each character to lower case to simplify checking for vowels. Using a frequency array of 5 elements provides a simple way to track the number of different vowels found in each word. Then a final test to see if the number of vowels found equals the required number is all you need before incrementing your total word count for words with three different vowels.
A simple implementation would be something similar to:
#include <stdio.h>
enum { NREQD = 3, NVOWEL = 5, MAXC = 128 }; /* declare constants */
int main (void) {
char word[MAXC] = ""; /* word buffer */
size_t wordcnt = 0; /* words with 3 different vowels */
printf ("enter a word(s) below, [ctrl+d on blank line to end]\n");
for (;;) {
int vowels[NVOWEL] = {0}, /* frequency array */
vowelcnt = 0, /* vowels per-word */
rtn; /* scanf return */
if ((rtn = scanf ("%127s", word)) == EOF) /* chk EOF */
break;
for (int i = 0; word[i]; i++) { /* loop over each char */
if ('A' <= word[i] && word[i] <= 'Z') /* check upper */
word[i] ^= 'a' - 'A'; /* convert to lower */
switch (word[i]) { /* check if vowel */
case 'a': vowels[0] = 1; break;
case 'e': vowels[1] = 1; break;
case 'i': vowels[2] = 1; break;
case 'o': vowels[3] = 1; break;
case 'u': vowels[4] = 1; break;
}
}
for (int i = 0; i < NVOWEL; i++) /* loop over array */
if (vowels[i]) /* check index */
vowelcnt++; /* increment vowelcnt */
if (vowelcnt >= NREQD) /* do we have at least 3 vowels? */
wordcnt++; /* increment wordcnt */
}
printf ("\nThere are %zu words with %d different vowels.\n",
wordcnt, NREQD);
}
Example Use/Output
$ ./bin/vowelcnt
enter a word(s) below, [ctrl+d on blank line to end]
Everyone Understands That The Dictionary Doesn't Track
Words That Contain Vowels Like It Does Etimology.
There are 4 words with 3 different vowels.
Look things over and let me know if you have further questions.
You can use fgets to read a whole line. I don't know how you define a
paragraph though, do you mean just a long text or a collection of lines? You can
copy & paste multiple lines in the console and if you loop using fgets, then
you get all the lines. But allowing the user to enter multiple lines at once,
it's more tricky, because you should know how many lines the user will input.
That's why I'd say focus on reading the text line by line.
Your solution reads characters by characters and you are ignoring non-vowels.
That's OK, but you are not detecting words like you should do. The for loop
makes no sense, because in the first iteration you enter in a while loop that
is only going to leave when there are no more characters to read from stdin.
So the next iteration of the for loop will not enter the while loop and you
won't be reading anything any more.
You are also repeating too much code, I know you assignment says not to use your
own functions, but this can be improved with a simple look up table by creating
an array of chars using the characters as an index for the array. I'll explain
that in the code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
int main(void)
{
char line[1024];
// initializing look ups with 0
int lookup_vowels[1 << CHAR_BIT] = { 0 };
// using 'a', 'e' as index for the lookup table
// if you want to know if a character is a vowel,
// lookup_vowels[character] will be 1 if character is
// a vowel, 0 otherwise
lookup_vowels['a'] = lookup_vowels['e'] = lookup_vowels['i'] =
lookup_vowels['o'] = lookup_vowels['u'] = 1;
// for parsing word with strtok
const char *delim = " \t\r\n";
int num_of_words = 0;
printf("Enter some text, to end input press ENTER and then CTRL+D\n");
while(1)
{
if(fgets(line, sizeof line, stdin) == NULL)
break;
// parsing words
char *word = strtok(line, delim);
if(word == NULL)
continue; // the line has only delimiters, ignore it
do {
// will be access with the same principle as the lookup
// table, the character is the index
int present[1 << CHAR_BIT] = { 0 };
size_t len = strlen(word);
for(size_t i = 0; i < len; ++i)
{
// I'll explain later the meaning
int c = tolower(word[i]);
if(lookup_vowels[c])
present[c] = 1; // set the present for a vowel to 1
}
int count = present['a'] + present['e'] + present['i'] + present['o']
+ present['u'];
if(count > 2)
{
printf("'%s' has more than three distinct vowels\n", word);
num_of_words++;
}
} while((word = strtok(NULL, delim)));
}
printf("The number of word with three or more distinct vowels: %d\n", num_of_words);
return 0;
}
So let me quickly explain some of the technique I use here:
The lookup table is an array of size 256 because a char is 8-bit1
value and can have 256 different values (range [0,255]). The idea is that this
array is initialized with 0 overall (int lookup_vowels[1<<CHAR_BIT] = { 0 };) and then
I set to 1 only in 5 places: at the position of the vowels using their
ASCII value as index.
So instead of doing the repeating task if checking
// where c is a char
if(c == 'a' || c == 'A')
a=1;
}
for all vowels, I just can do
int idx = tolower(c);
if(lookup_vowels[idx])
{
// c is a vowel
}
The present variable function similar to the lookup table, here I use the
ASCII code of a vowel as index and set it to 1 if a vowel is present in word.
After scanning all characters in word, I sum all values stored in present.
If the value is greater than 2, then the word has at least 3 or more distinct
vowels and the counter variable is increased.
The function strtok is used to split the line using a defined set of
delimiters, in this case the empty character, tab, carriage return and line
feed. To start parsing the line, strtok must be called with the source string
as the first argument and the delimiters as the second argument. All other
subsequent calls must pass NULL as the first argument. The function returns a
pointer to the next word and returns NULL when no more words have been found.
When a word is found, it calculates the number of distinct vowels and checks if
this number is greater than 2.
fotenotes
1CHAR_BIT defined in limits.h returns the number of bits of byte.
Usually a byte is 8-bit wide, so I could have written 256 instead. But there are
"exotic" architectures where a byte is not 8-bit long, so by doing 1<<CHAR_BIT
I'm getting the correct dimension.

Converting user input to an array of characters, and filtering letters from other characters?

#include "stdafx.h"
#include "stdlib.h"
#include <ctype.h>
int num = 0;
int i = 0;
int ch = 0;
int letter_index_in_alphabet(int ch) {
if (isalpha(ch) == true) {
char temp_str[2] = { ch };
num = strtol(temp_str, NULL, 36) - 9;
printf("%d is a letter, with %d as its location in the alphabet!", ch, num);
}
else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 10 letters and numbers: \n");
fgets(input_str, 10, stdin);
for (i == 0; i <= 10; i++) {
ch = input_str[i];
letter_index_in_alphabet(ch);
}
return 0;
}
Hello everyone, this is my first post on SOF! The goal of this program is to read characters from the standard input to EOF. For each character, report if it is a letter. If it is a letter, print out its respective index in the alphabet ('a' or 'A' = 1, 'b' or 'B' = 2..etc). I have been searching some other posts on stackoverflow and this has helped me get this far(using fgets and strtol functions). I have no visible syntax errors when I run this code, but after I enter a string of characters (ex: 567gh3fr) the program crashes.
Basically, I am trying to use 'fgets' to bring each character entered into a string with the appropriate index. Once I have that string, I check each index for a letter and if it is, I print the number assigned to that letter of the alphabet.
Any help or insight into why this isn't working as intended is greatly appreciated, Thanks!
You have a few problems.
First, char input_str[10] is only big enough for the user to enter 9 characters, not 10, because you need to allow one character for the null byte that ends a string.
Second, your loop goes too far. For a string with 10 characters, indexes go up to 9, not 10. It also should stop when it gets to the null byte, since the user might not have entered all 9 characters.
To get the position in the alphabet, you can simply subtract the value of A or a from the value of the character. Use tolower() or toupper() to convert the character to the case that you're going to use. Your method works, but it's overly complicated and confusing.
letter_index_in_alphabet() is declared to return int. But when the character is a letter, it doesn't execute a return statement. I'm not sure why it's supposed to return something, since you never use the return value, but I've changed it to return the position (maybe the caller should be the one that prints the message, so the function just does the calculation).
In the for loop, it should be i = 0 to perform an assignment, not i == 0 which is comparison.
You also shouldn't use global variables so much. And system header files should have <> around them, not "".
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int letter_index_in_alphabet(int ch) {
if (isalpha(ch)) {
int num = tolower(ch) - 'a' + 1;
printf("%d is a letter, with %d as its location in the alphabet!\n", ch, num);
return num;
} else {
return -1;
}
}
int main()
{
char input_str[10];
printf("Please enter a series of up to 9 letters and numbers: \n");
fgets(input_str, sizeof(input_str), stdin);
for (int i = 0; input_str[i]; i++) {
letter_index_in_alphabet(input_str[i]);
}
return 0;
}

Resources