-3

我试图弄清楚如何使用指针来使用 toupper 和 tolower。我以为我走在正确的轨道上。我设法让大写字母的指针正确,但由于某种原因,它不适用于小写字母。任何意见将是有益的。

#include <stdio.h>
#include <ctype.h>
void safer_gets (char array[], int max_chars);

main()
{

    /* Declare variables */
    /* ----------------- */
    char  text[51];
    char *s1_ptr = text;
    int   i;

    /* Prompt user for line of text */
    /* ---------------------------- */
    printf ("\nEnter a line of text (up to 50 characters):\n");
    safer_gets(text ,50);


    /* Convert and output the text in uppercase characters. */
    /* ---------------------------------------------------- */
    printf ("\nThe line of text in uppercase is:\n");
    while (*s1_ptr != '\0') 
        {
            *s1_ptr = toupper(*s1_ptr);          
            putchar(toupper(*s1_ptr++));
        }

    /* Convert and output the text in lowercase characters. */
    /* ---------------------------------------------------- */
    printf ("\n\nThe line of text in lowercase is:\n");
    while (*s1_ptr != '\0') 
        {
            *s1_ptr = tolower(*s1_ptr);          
            putchar(tolower(*s1_ptr++));
        }

    /* Add carriage return and pause output */
    /* ------------------------------------ */
    printf("\n");
    getchar();
} /* end main */

/* Function safer_gets */
/* ------------------- */
void safer_gets (char array[], int max_chars)
{
    /* Declare variables. */
    /* ------------------ */
    int i;

    for (i = 0; i < max_chars; i++)
        {
            array[i] = getchar();

            /* If "this" character is the carriage return, exit loop */
            /* ----------------------------------------------------- */
            if (array[i] == '\n')
                break;
        } /* end for */

    if (i == max_chars )
        if (array[i] != '\n')
            while (getchar() != '\n');
    array[i] = '\0';
} /* end safer_gets */
4

1 回答 1

1

那是因为它永远不会进入第二个循环,因为您修改了指针。在第二个循环将您的指针重置为 s1_ptr = text 之前,它将起作用。

于 2017-03-03T09:26:45.370 回答