大写字符,toupper的工作原理

capitalizing characters, how toupper works?

本文关键字:工作 toupper 字符      更新时间:2023-10-16

我需要使用一个字符数组,并根据需要将数组中的字符大写和小写。我在看巨嘴鸟和它的例子,但我对它的工作原理感到困惑。从cplusplus.com上给出的例子来看,我写了

int main(){
    int i = 0;
    char str[] = "This is a test.";
    while(str[i]){
        putchar(toupper(str[i]));
        i++;
    }
    for(int i = 0; i < 15; i++){
        cout << str[i];
    }
}

有两件事我不明白。第一个是,如果没有底部的cout,程序就会打印出"这是一个测试"。putchar是否打印到屏幕上?(示例中没有解释putchar的使用)。但我的第二个更重要的问题是,为什么底部的cout仍然打印出来这是一个测试。?它不会更改str[]中的字符吗?有没有其他方法可以做到这一点(请记住,我需要使用字符数组)?

是的,putchar()将一个字符打印到程序的标准输出中。这就是它的目的。它是大写输出的来源。

程序底部的cout打印原始字符串,因为您从未修改过它。toupper()函数不会——实际上不能——修改其参数。相反,它返回大写字符。

putchar将单个字符写入输出:http://www.cplusplus.com/reference/cstdio/putchar/

因此,第一个while循环将每个字符从str一次一个转换为大写并输出。然而,它并没有改变str的内容——这解释了第二个循环的小写输出。

编辑:

我已经扩展了第一个循环:

// Loop until we've reached the end of the string 'str'
while(str[i]){
    // Convert str[i] to upper case, but then store that elsewhere. Do not modify str[i].
    char upperChar = toupper(str[i]);
    // Output our new character to the screen
    putchar(upperChar);
    i++;
}