Home > Enterprise >  im trying to create a program to reverse a string and if the string has uppercase i must change it t
im trying to create a program to reverse a string and if the string has uppercase i must change it t

Time:12-11

im trying to create a program to reverse a string and if the string has uppercase i must change it to lowercase and vice versa but when i use scanf[^\n] it cant input anything. the input process only succeed in first input

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
    int ctr1, ctr2, loop1, loop2;
    char char1[1010];
    char upp[1010], low[1010];
    int len;
    scanf("%d", &loop1);

    for (ctr1 = 0; ctr1 < loop1; ctr1  ) {
        scanf("%[^\n]", char1);
        len = strlen(char1);
            
        for(ctr2=0;ctr2<len;ctr2  ){
            upp[ctr2] = toupper(char1[ctr2]);
            low[ctr2] = tolower(char1[ctr2]);

            if (char1[ctr2] == low[ctr2]) {
                char1[ctr2] = upp[ctr2];
            }
            else if (char1[ctr2] == upp[ctr2]) { 
                char1[ctr2] = low[ctr2];
            }
        }
            
        printf("Case #%d: ", ctr1   1);
        
        for (ctr2 = len - 1; ctr2 >= 0; ctr2--) {
            printf("%c", char1[ctr2]);
        }
        
        printf("\n");
    }
}

CodePudding user response:

The line

scanf("%[^\n]",char1);

will read everything in the line except for the newline character at the end of the line. When you run this line of code again in the next loop iteration, it will read nothing, because the newline character is still in the input stream.

For this reason, you must also remove the newline character from the input stream.

One simple way of doing this would be to make an additional call to getchar after every scanf call.

Another way of doing this is to instruct scanf to remove all whitespace characters (which includes newline characters) before attempting to match the input, like this:

scanf(" %[^\n]",char1);

However, using the scanf format specifiers %s or %[] without setting a maximum limit is generally not recommended, because a buffer overflow is possible. Therefore, in your case, it would be safer to write

scanf(" 09[^\n]",char1);

to limit the number of matched characters to 1009, so that the total number of bytes written is limited to 1010 (including the terminating null character). That way, you can be sure that you won't be writing to the array out of bounds.

However, generally I recommend that you use the function fgets instead of scanf, as that function's behavior is more intuitive, as it always reads a whole line at a time (assuming that the provided memory buffer is large enough to store the entire line), including the newline character at the end of the line.

  •  Tags:  
  • c
  • Related