c - 带指针的 toupper 和 tolower

标签 c pointers toupper tolower

我试图弄清楚如何使用指针来使用 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 */

最佳答案

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

关于c - 带指针的 toupper 和 tolower,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497041/

相关文章:

c++ - 按类型比较指针?

java - 链表toUppercase方法返回类型错误

python - 将字节串输入到 C 程序用户输入中

c - 在 C 中获取 LAN 上的设备列表

c - 如何使用 libxml2 深入解析 xml 文件

c++ - 从文件中读取输入,将第一个字母大写,将其他字母小写,然后输出到单独的文件中

c++ - 在调用 toupper()、tolower() 等之前,我是否需要转换为 unsigned char?

c - int i() 有什么用

c++ - 你能取消引用整数文字吗?

c - 将 void * 值设置为 intptr_t 变量是否需要显式转换?