tags:

views:

74

answers:

3

i made a program which converts lower case to upper case a string.i know how to convert a char to upper case via preprocessor directives but i dont know how to do it for a string.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define UPPER([])  ([]-32)
void fstring_convert(char string[]);
void main(void)
{
char string[40];
printf("Enter a string:");
gets(string);
fstring_convert(string);
printf("%s",string);
getch();
}

void fstring_convert(char string[])
{
    int i;
 for(i=0; ;i++)
 {
    if(string[i]==' ')
    {
        string[i]=string[i+1];
    }
    if(isdigit(string[i]))
    {
    string[i]+=1;
    }
    UPPER('string[i]');
    if(string[i]=='\0')
    break;
 }

}
+3  A: 

You should use the C standard library function toupper() on each character of the string (in a loop). This function has the advantage of correctly handling non-alphabetic characters.

James McNellis
i am told to use preprocessor directives
fahad
@fahad: That is a most unusual requirement. There's always the option of `#define my_toupper(x) toupper(x)`.
James McNellis
you mean i can call a built in function within the preprocessor?
fahad
@fahad: Do you know what the preprocessor does? If not, you should consult your C book.
James McNellis
+3  A: 

Preprocessors do not have loops.

Thus, for a string of arbitrary length, you cannot convert all characters to upper case with a preprocessor macro.

The code you have above is buggy because your macro should look like:

#define TOUPPER(x) x = (x>='a' && x<='z')?(x-32):x;

And then call TOUPPER(string[i]) in your for loop.

But I don't see what the point of the macro is.

Borealid
+2  A: 

This homework assignment is to teach you about ascii and type conversion.

Loop through the string one letter at a time. For each letter, lookup the ascii code for the letter, (find the offset to uppercase do this once while coding and store in a constant), then add the offset to the letter.

Hint: a char can be cast as an int.

Byron Whitlock