I'm trying to create a function that will identify whether the first letter input is upper or lower case then output the rest of the string in that same case(upper/lower).
For example, "Hi there" would become "HI THERE".
I'm not familiar with fgets. Once I run it I can input and press enter and the program doesn't run. I'm not getting any compiler errors. I believe I went wrong in the void shift function.
Also, I know gets is not recommended, is fgets similar? Or is it better to use scanf?
#include <stdio.h>
#include <ctype.h>
void shift (char *my_string); // Function declaration
int main()
{
char inputstring[50];
printf("Enter a string\n");
char *my_string = inputstring;
shift(my_string); // Function
}
void shift (char *my_string) // Function definition
{
int i =0;
char ch;
for(i=0; i<50; i++)
fgets(my_string, 50, stdin);
while(my_string[i])
{
if(ch>='A' && ch<= 'Z') // When first char is uppercase
{
putchar (toupper(my_string[i]));
i++;
}
else if (ch>='a' && ch <= 'z') // When first char is lowercase
{
putchar(tolower(my_string[i]));
i++
}
}
return;
}
You don't need to call fgets() fifty times. It reads a line from stdin and writes it to my_string. It seems you only want to read one line, not fifty (and keep only the last one). The 50 is the maximum number of characters (minus one) that will be read and written to the buffer. This limit is to prevent buffer overflow. See fgets().
Try removing the for loop on the line before the fgets() call. Also, you don't need the my_string in main(). The corrected code:
#include <stdio.h>
#include <ctype.h>
void shift (char *my_string);//function declaration
int main()
{
char inputstring[50];
printf("Enter a string\n");
shift(inputstring);
}
void shift (char *my_string) //function definition
{
int i;
char ch;
if ( fgets(my_string, 50, stdin) == NULL )
return;
ch = my_string[0];
for ( i=0; my_string[i]; i++ )
{
if(ch>='A' && ch<= 'Z') //when first char is uppercase
{
putchar (toupper(my_string[i]));
}
else if (ch>='a' && ch <= 'z')//when first char is lowercase
{
putchar(tolower(my_string[i]));
}
}
return;
}
Edit: Added ch initialization, pointed out by #thurizas. Changed while loop to for loop. Added check to return value of fgets() as suggested by #JonathanLeffler. (See his comment about the buffer size.)
Here is another solution for your problem,
#include <stdio.h>
#include <ctype.h>
void convertTo (char *string);
int main()
{
char inputString[50];
printf("Enter a string\n");
convertTo(inputString);
}
void convertTo (char *string)
{
int i;
char ch;
gets(string);
ch = string[0];
for ( i=0; string[i]; i++ )
{
if(ch>='A' && ch<= 'Z')
{
if(string[i]>='a' && string[i]<= 'z')
string[i] = string[i] - 32;
}
else if (ch>='a' && ch <= 'z')
{
if(string[i]>='A' && string[i]<= 'Z')
string[i] = string[i] + 32;
}
}
printf("%s\n", string);
return;
}
All ASCII characters are represented by 7-bits. (thus the term 7-bit ASCII) The only bitwise difference between lower-case and upper-case is that bit-5 (the sixth bit) is set for lowercase and cleared (unset) for uppercase. This allows a simple bitwise conversion between lowercase and uppercase (either by adding/subtracting 32 or by simply flipping bit-5 directly.)
+-- lowercase bit
|
a = 01100001 A = 01000001
b = 01100010 B = 01000010
c = 01100011 C = 01000011
...
This allows a simple test and conversion if the first character is upper-case:
#include <stdio.h>
enum { MAXC = 50 };
char *shift (char *my_string);
int main (void)
{
char inputstring[MAXC] = {0};;
printf ("\n Enter a string: ");
if (shift (inputstring))
printf (" my_string is : %s\n", inputstring);
return 0;
}
char *shift (char *my_string)
{
char *p;
if (!(p = fgets (my_string, MAXC, stdin))) return NULL;
if (*p == '\n') return NULL; /* Enter only pressed */
if ('A' <= *p && *p <= 'Z') /* test for upper case */
for (; *p; p++) /* convert lower/upper */
if ('a' <= *p && *p <= 'z') *p &= ~(1 << 5);
return my_string;
}
Example Use
$ ./bin/case_1st_to_upper
Enter a string: this is my string
my_string is : this is my string
$ ./bin/case_1st_to_upper
Enter a string: This is my string
my_string is : THIS IS MY STRING
Related
I am trying to pass a C string (char*) to a function lower(char *) (as in the prototype) that returns a C string char *lower() to main(). But I am not getting the desired output. Point out my mistakes and suggest some techniques for getting the result.
(Note : <string.h> functions are not allowed & the task must be done with pointers). Here is my code,
#include <stdio.h>
#include <stdlib.h>
char *lower(char *);
void main() {
char pass[10], *pass1;
printf("Enter a password\n");
scanf("%s", pass);
pass1 = lower(pass);
printf("Lower case ");
int i = 0;
while (*pass1 != '\0') {
printf("%c", *(pass1 + i));
i++;
}
}
char *lower(char *p) {
while (*p != '\0') {
if (*p >= 'A' && *p <= 'Z') {
*p = *p + 32;
}
p++;
}
return p;
}
There are multiple problems in your code:
main should have the prototype int main(void) a for good style have a return 0; statement at the end of the body.
scanf() should protect the destination array from overflow by specifying the maximum number of characters to read into it: scanf("%9s", pass); and you should check its return value for successful conversion.
you should use pass1[i] instead of *(pass1 + i). Both expressions are equivalent but the first is more readable. Incidentally, another equivalent but surprising alternative is i[pass1], don't use it unless you want to confuse the reader, which might be advisable in a password handling routine.
printing individual characters with printf("%c", pass1[i]) does not seem mandated by the rules posted: use a single printf statement.
Furthermore, the loop test is constant: while (*pass1 != '\0') as you only increment i in the loop. Hence an infinite loop and undefined behavior when you access elements of pass beyond its end.
as you pass the return value to printf(), function lower() should return the original pointer, not the pointer to the end of the argument string.
you should not hard-code the difference between lowercase and uppercase characters, 32 only works for ASCII, not EBCDIC. *p += 'a' - 'A'; would be both more portable and more readable. It works for both ASCII and EBCDIC, but might not for other less common character sets and the test if (*p >= 'A' && *p <= 'Z') is not precise enough for EBCDIC as the uppercase letters do not form a contiguous set. Use the macros from <ctype.h> for a portable solution.
Here is a corrected version:
#include <stdio.h>
#include <ctype.h>
char *lower(char *);
int main(void) {
char pass[80];
printf("Enter a password\n");
if (scanf("%79s", pass) == 1) {
printf("Lower case: %s\n", lower(pass));
}
return 0;
}
char *lower(char *s) {
for (char *p = s; *p != '\0'; p++) {
*p = tolower((unsigned char)*p);
}
return s;
}
If you cannot use <ctype.h>, use this less portable version:
char *lower(char *s) {
for (char *p = s; *p != '\0'; p++) {
if (*p >= 'A' && *p <= 'Z')
*p += 'a' - 'A';
}
return s;
}
char *lower(char *p){
char *ptr = p;
while(*p != '\0'){
if( *p>='A' && *p<='Z' ){
*p = *p + 32;
}
p++;
}
return ptr;
}
why sometimes is good to return something like converted char pointer - to use it in other operations - for example as a parameter in another function call.
What I am trying to code is, if I input camelcase, it should just print out camelcase, but if there contains any uppercase, for example, if I input camelCase, it should print out camel_case.
The below is the one I am working on but the problem is, if I input, camelCase, it prints out camel_ase.
Can someone please tell me the reason and how to fix it?
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
char input[100];
int i = 0;
while ((ch = getchar()) != EOF) {
input[i] = ch;
if (isupper(input[i])) {
input[i] = '_';
//input[i+1] = tolower(ch);
} else {
input[i] = ch;
}
printf("%c", input[i]);
i++;
}
}
First look at your code and think about what happens when someone enters a word longer than 100 characters -> undefined behavior. If you use a buffer for input, you always have to add checks so you don't overflow this buffer.
But then, as you directly print the characters, why do you need a buffer at all? It's completely unnecessary with the approach you show. Try this:
#include <stdio.h>
#include <ctype.h>
int main()
{
int ch;
int firstChar = 1; // needed to also accept PascalCase
while((ch = getchar())!= EOF)
{
if(isupper(ch))
{
if (!firstChar) putchar('_');
putchar(tolower(ch));
} else
{
putchar(ch);
}
firstChar = 0;
}
}
Side note: I changed the type of ch to int. This is because getchar() returns an int, putchar(), isupper() and islower() take an int and they all use a value of an unsigned char, or EOF. As char is allowed to be signed, on a platform with signed char, you would get undefined behavior calling these functions with a negative char. I know, this is a bit complicated. Another way around this issue is to always cast your char to unsigned char when calling a function that takes the value of an unsigned char as an int.
As you use a buffer, and it's useless right now, you might be interested there is a possible solution making good use of a buffer: Read and write a whole line at a time. This is slightly more efficient than calling a function for every single character. Here's an example doing that:
#include <stdio.h>
static size_t toSnakeCase(char *out, size_t outSize, const char *in)
{
const char *inp = in;
size_t n = 0;
while (n < outSize - 1 && *inp)
{
if (*inp >= 'A' && *inp <= 'Z')
{
if (n > outSize - 3)
{
out[n++] = 0;
return n;
}
out[n++] = '_';
out[n++] = *inp + ('a' - 'A');
}
else
{
out[n++] = *inp;
}
++inp;
}
out[n++] = 0;
return n;
}
int main(void)
{
char inbuf[512];
char outbuf[1024]; // twice the lenght of the input is upper bound
while (fgets(inbuf, 512, stdin))
{
toSnakeCase(outbuf, 1024, inbuf);
fputs(outbuf, stdout);
}
return 0;
}
This version also avoids isupper() and tolower(), but sacrifices portability. It only works if the character encoding has letters in sequence and has the uppercase letters before the lowercase letters. For ASCII, these assumptions hold. Be aware that what is considered an (uppercase) letter could also depend on the locale. The program above only works for letters A-Z as in the english language.
I don't know exactly how to code in C but I think you should do something like this.
if(isupper(input[i]))
{
input[i] = tolower(ch);
printf("_");
} else
{
input[i] = ch;
}
There are two problems in your code:
You insert one character in each branch of if, while one of them is supposed to insert two characters, and
You print characters as you go, but the first branch is supposed to print both _ and ch.
You can fix this by incrementing i on insertion with i++, and by printing the entire word at the end:
int ch; // <<== Has to be int, not char
char input[100];
int i = 0;
while((ch = getchar())!= EOF && (i < sizeof(input)-1)) {
if(isupper(ch)) {
if (i != 0) {
input[i++] = '_';
}
ch = tolower(ch);
}
input[i++] = ch;
}
input[i] = '\0'; // Null-terminate the string
printf("%s\n", input);
Demo.
There are multiple problems in your code:
ch is defined as a char: you cannot properly test for end of file if c is not defined as an int. getc() can return all values of type unsigned char plus the special value EOF, which is negative. Define ch as int.
You store the byte into the array input and use isupper(input[i]). isupper() is only defined for values returned by getc(), not for potentially negative values of the char type if this type is signed on the target system. Use isupper(ch) or isupper((unsigned char)input[i]).
You do not check if i is small enough before storing bytes to input[i], causing a potential buffer overflow. Note that it is not necessary to store the characters into an array for your problem.
You should insert the '_' in the array and the character converted to lowercase. This is your principal problem.
Whether you want Main to be converted to _main, main or left as Main is a question of specification.
Here is a simpler version:
#include <ctype.h>
#include <stdio.h>
int main(void) {
int c;
while ((c = getchar()) != EOF) {
if (isupper(c)) {
putchar('_');
putchar(tolower(c));
} else {
putchar(c);
}
}
return 0;
}
To output the entered characters in the form as you showed there is no need to use an array. The program can look the following way
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int c;
while ((c = getchar()) != EOF && c != '\n')
{
if (isupper(c))
{
putchar('_');
c = tolower(c);
}
putchar(c);
}
putchar('\n');
return 0;
}
If you want to use a character array you should reserve one its element for the terminating zero if you want that the array would contain a string.
In this case the program can look like
#include <stdio.h>
#include <ctype.h>
int main( void )
{
char input[100];
const size_t N = sizeof(input) / sizeof(*input);
int c;
size_t i = 0;
while ( i + 1 < N && (c = getchar()) != EOF && c != '\n')
{
if (isupper(c))
{
input[i++] = '_';
c = tolower(c);
}
if ( i + 1 != N ) input[i++] = c;
}
input[i] = '\0';
puts(input);
return 0;
}
Reposting because my first post was no good. I have a question that I'm not really sure how to do. I know the process I'm going for, but am not totally sure how to scan a string into an array so that each character/integer is scanned into a independent element of the array. I'll post the question and the code I have so far, and any help would be appreciated.
Question:
Assume that we have a pattern like the following: ([n][letter])+ in which n is an integer number and letter is one of the lowercase letters from a-z. For example, 2a and 3b are valid expressions based on our pattern. Also, “+” at the end of the pattern means that we have at least one expression (string) or more than one expression attached. For instance, 2a4b is another valid expression which is matched with the pattern. In this question, we want to convert these valid expressions to a string in which letters are repeated n times.
o Read an expression (string) from user and print the converted version of the expression in the output.
o Check if input expression is valid. For example, 2ab is not a valid expression. If the expression is not valid, print “Invalid” in the output and ask user to enteranother expression.
o Sample input1 = “2a”, output = aa
o Sample input2 = “2a3b”, output = aabbb
o You will receive extra credit if you briefly explain what concept or theory you can use to check whether an expression is valid or not.
What I have so far:
#include <stdio.h>
int main()
{
int size, i, j;
char pattern[20];
char vowel[20];
int count[20];
printf("Please enter your string: ");
gets(pattern);
size = strlen(pattern);
for(i=0; i<size; i++)
if((i+1)%2 == 0)
vowel[i] = pattern[i];
else if((i+1)%2 != 0)
count[i] = pattern[i];
for(i=0; i<size/2; i++);
for(j=0; j<count[i]; j++)
printf("%s", vowel[i]);
}
I assumed you want to write the "invalid\n" string on stderr. If not just change the file descriptor given to write.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT_SIZE 20
int
check_input(char *input)
{
while (*input)
{
if (*input < '0' || *input > '9')
{
write(2, "invalid\n", 8);
return 1;
}
while (*input >= '0' && *input <= '9')
input++;
if (*input < 'a' || *input > 'z')
{
write(2, "invalid\n", 8);
return 1;
}
input++;
}
return 0;
}
void
print_output(char *input)
{
int i;
while (*input)
{
i = atoi(input);
while (*input >= '0' && *input <= '9')
input++;
for (; i > 0; i--)
write(1, input, 1);
input++;
}
write(1, "\n", 1);
}
int
main()
{
char input[MAX_INPUT_SIZE];
do
{
printf("Please enter your string: ");
fgets(input, MAX_INPUT_SIZE, stdin);
input[strlen(input) - 1] = '\0';
}
while (check_input(input));
print_output(input);
return 0;
}
The steps are:
Read pattern
Check if pattern is valid
Generate output
Since the input length is not specified you have to assume a maximum length.
Another assumption is n is a single digit number.
Now you may read the whole expression with fgets() or read it char by char.
The latter allows you to check for validity as you read.
Lets use fgets() for convenience and in case the expression needs to be stored for later use.
char exp[100]; // assuming at most 50 instances of ([n][letter])
int len;
printf("Input: ");
fgets(exp, 100, stdin);
len = strlen(exp) - 1; // Discard newline at end
An empty input is invalid. Also a valid expression length should be even.
if (len == 0 || len%2 != 0) {
printf("Invalid-len\n");
return 1;
}
Now parse the expression and separately store numbers and letters in two arrays.
char nums[50], letters[50];
invalid = 0;
for (i = 0, j = 0; i < len; i += 2, j++) {
if (exp[i] >= '1' && exp[i] <= '9') {
nums[j] = exp[i] - '0';
} else {
invalid = 1;
break;
}
if (exp[i+1] >= 'a' && exp[i+1] <= 'z') {
letters[j] = exp[i+1];
} else {
invalid = 1;
break;
}
}
Notice that in each iteration if first char is not a number or second char is not a letter, then the expression is considered to be invalid.
If the expression is found to be invalid, nothing to do.
if (invalid) {
printf("Invalid\n");
return 1;
}
For a valid expression run nested loops to print the output.
The outer loop iterates for each ([n][letter]) pattern.
The inner loop prints n times the letter.
printf("Output: ");
for (i = 0; i < len/2; i++) {
for (j = 0; j < nums[i]; j++)
printf("%c", letters[i]);
}
This is a rather naive way to solve problems of this type. It is better to use regular expressions.
C standard library doesn't have regex support. However on Unix-like systems you can use POSIX regular expressions.
like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#define prompt "Please enter your string: "
void occurs_error(const char *src, const char *curr){
printf("\nInvalid\n");
printf("%s\n", src);
while(src++ != curr){
putchar(' ');
}
printf("^\n");
}
bool invalid(char *pattern){
char *p = pattern;
while(*p){
if(!isdigit((unsigned char)*p)){//no number
occurs_error(pattern, p);
break;
}
strtoul(p, &p, 10);
if(!*p || !islower((unsigned char)*p)){//no character or not lowercase
occurs_error(pattern, p);
break;
}
++p;
}
return *p;
}
int main(void){
char pattern[20];
while(fputs(prompt, stdout), fflush(stdout), fgets(pattern, sizeof pattern, stdin)){
pattern[strcspn(pattern, "\n")] = 0;//chomp newline
char *p = pattern;
if(invalid(p)){
continue;
}
while(*p){
int n = strtoul(p, &p, 10);
while(n--)
putchar(*p);
++p;
}
puts("");
}
}
I'm trying to program a loop that counts characters until it receives a certain sentinel value. The sentinel value is supposed to be a #, but I've also tried a 0 and a Z and had the same response.
When it compiles, I receive "warning: comparison between pointer and integer" for lines 16 (the line that calls the sentinel.)
If I don't define the sentinel, but instead rely on logical operators in the while statement, then I receive no error, but have an endless loop.
Thanks!
#include <stdio.h>
int main()
{
#define SENTINEL '#'
char ch;
int chcount;
printf("Enter your text, terminate with a #:");
scanf("%s", &ch);
chcount = 0;
while (ch != SENTINEL)
{
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount +1;
printf("You have entered %d characters", chcount);
}
}
return(0)
}
With the %s format specifier, scanf expects the address of a char buffer, where the string you type will be copied.
And you gave the address &ch of a single char, which is obviously not enough to contain a "word" from input with its terminating null character.
Moreover, your loop reads no input from the user. Thus the endless loop.
This is because the way you use scanf(), with %s format specifier you are writing to a char*, not the char ch (as you've declared). In order to write to a single char variable, you should use a %c format specifier.
To fix this you should either use f.e. getchar() instead of scanf() or use scanf() (and change ch to char* then) but iterate over scanned string to check whether there is #.
I would recommend the first solution.
The while loop never ends so I changed your while loop.
I tried to change your program to:
#include <stdio.h>
#define SENTINEL '#'
int main()
{
char ch;
int chcount;
printf("Enter your text, terminate with a #:");
chcount = 0;
while ((ch = getchar()) != SENTINEL)
{
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount + 1;
printf("You have entered %d characters\n", chcount);
}
}
return(0);
}
Some issues I found with your code:
scanf("%s", &ch);
It should be
scanf("%c", &ch);
Next, semicolon missing here: return(0);
However, since your aim is:
I'm trying to program a loop that counts characters until it receives a certain sentinel value. The sentinel value is supposed to be a #
I suggest moving your scanf() inside while loop:
#include <stdio.h>
int main()
{
#define SENTINEL '#'
char ch='0';
int chcount;
printf("Enter your text, terminate with a #:");
chcount = 0;
int i=0;
while (ch != SENTINEL)
{ scanf("%c", &ch);
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount +1;
printf("You have entered %d characters", chcount);
i++;
}
}
return(0);
}
here is a working version of the posted code.
It contains numerous corrections.
Corrections include consistent/usable indentation and logic corrections
Note: not all implementations have the getline() function
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int sentinelFound = 0;
#define SENTINEL '#'
char* line = NULL;
size_t lineLen = 0;
printf("Enter your text, terminate with a #:");
int chcount;
getline(&line, &lineLen, stdin );
size_t i;
for( i=0; i<lineLen; i++)
{
if( SENTINEL == line[i] )
{
sentinelFound = 1;
break;
}
if ((line[i] >= 'A') && (line[i] <= 'Z')) // only count capital letters
{
chcount = chcount +1;
}
}
free( line );
if( !sentinelFound )
printf( "You did not enter the sentinel character!" );
else
printf("You have entered %d capital characters\n", chcount);
return(0);
} // end function: main
I'm new to C and programming. I got stuck at a homework exercise. My output only shows the first character in upper case, and the following characters in some weird numbers. Can someone take a look at my code and give me some tips on what I've done wrong and ways to fix the issue? Your help is greatly appreciated!
"Write a function void sticky(char* word) where word is a single word such as “sticky” or “RANDOM”. sticky() should modify the word to appear with “sticky caps” (http://en.wikipedia.org/wiki/StudlyCaps), that is, the letters must be in alternating cases(upper and lower), starting with upper case for the first letter. For example, “sticky” becomes “StIcKy” and “RANDOM” becomes “RaNdOm”. Watch out for the end of the string, which is denoted by ‘\0’. You can assume that legal strings are given to the sticky() function."
#include <stdio.h>
#include <stdlib.h>
/*converts ch to upper case, assuming it is in lower case currently*/
char toUpperCase(char ch)
{
return ch-'a'+'A';
}
/*converts ch to lower case, assuming it is in upper case currently*/
char toLowerCase(char ch)
{
return ch-'A'+'a';
}
void sticky(char* word){
/*Convert to sticky caps*/
for (int i = 0; i < sizeof(word); i++)
{
if (i % 2 == 0)
{
word[i] = toUpperCase(word[i]);
}
else
{
word[i] = toLowerCase(word[i]);
}
}
}
int main(){
/*Read word from the keyboard using scanf*/
char word[256];
char *input;
input = word;
printf("Please enter a word:\n");
scanf("%s", input);
/*Call sticky*/
sticky(input);
/*Print the new word*/
printf("%s", input);
for (int i = 0; i < sizeof(input); i++)
{
if (input[i] == '\n')
{
input[i] = '\0';
break;
}
}
return 0;
}
you need to use strlen not sizeof to find the length of a char* string
Modify your change upper and change lower function
/*converts ch to upper case,*/
char toUpperCase(char ch)
{
if(ch>='a' && ch<='z')/*If condition just to make sure current letter is in lower case*/
return ch-'a'+'A';
}
/*converts ch to lower case, assuming it is in upper case currently*/
char toLowerCase(char ch)
{
if(ch>='A' && ch<='Z')/*If condition just to make sure current letter is in Upper case*/
return ch-'A'+'a';
}
Also, only four characters are converted since you are using sizeof for finding the string length.sizeof always returns 4(depends upon machine).
use strlen(word) to find the length of string word in following for loop:
for (int i = 0; i < strlen(word); i++)
{
}
You should use strlen instead of sizeof.
Also, you must check whether your letter is already upper or lower case:
for (int i = 0; i < strlen(word); i++)
{
if (i % 2 == 0)
{
if ( isLowerCase(word[i]) )
{
word[i] = toUpperCase(word[i]);
}
else
{
// do nothing.
}
}
else
{
if ( isUpperCase(word[i]) )
{
word[i] = toLowerCase(word[i]);
}
else
{
// do nothing.
}
}
}
Note that I haven't implemented the isUpperCase and isLowerCase functions ;D
Function sizeof() is used to calculate the size of the datatype, not the size allocated to the pointer.
So you can not use it like sizeof(word). Instead, iterate over a characters until you stumble upon a \0, which indicates end of string.
On example:
int i = 0;
while ( word[i] != 0 ) {
// do lower/upper case conversion.
}
sizeof (word) is the size of a char *, you must pass another parameter with the array size... or use strlen ().
Something is wrong in your code : you are making odd characters upper case and even ones lower but you do no check whether they were lower or upper case in the first place. But lowering an already lower-case letter gives you a wrong value (the same is true for "uppering" an already upper-case letter).
So you should do :
char toUpperCase(char ch)
{
if ((ch >= 'a') && (ch <= 'z')) {
return ch-'a'+'A';
} else {
return ch;
}
}
and the same for toLowerCase.
Thank you so much for the tips! Using your suggestions, I modified my code and it's working now.
Below is my revised code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*converts ch to upper case, assuming it is in lower case currently*/
char toUpperCase(char ch){
return ch-'a'+'A';
}
/*converts ch to lower case, assuming it is in upper case currently*/
char toLowerCase(char ch){
return ch-'A'+'a';
}
void sticky(char* word)
{
/*Convert to sticky caps*/
for (int i = 0; i < strlen(word); i++)
{
if (i % 2 == 0)
{
if (word[i] >= 'a' && word[i] <= 'z')
{
word[i] = toUpperCase(word[i]);
}
}
else
{
if (word[i] >= 'A' && word[i] <= 'Z')
{
word[i] = toLowerCase(word[i]);
}
}
}
}
int main(){
/*Read word from the keyboard using scanf*/
char word[256];
char *input;
input = word;
printf("Please enter a word:\n");
scanf("%s", input);
/*Call sticky*/
sticky(input);
/*Print the new word*/
printf("%s", input);
for (int i = 0; i < sizeof(input); i++)
{
if (input[i] == '\n')
{
input[i] = '\0';
break;
}
}
return 0;
}