使用toupper功能输出C程序的奇怪输出

时间:2016-03-17 22:05:22

标签: c toupper

这是我的程序,用于标准从标准输入输入的所有字母。但有些输出很奇怪。例如,如果输入是" lorem ipsum"输出将是" LOREM IPSUMS?"。如果输入是单个字符,例如' m',输出将是" MZ#X?" 。 " S&#34?; " Z#X?"不应该在这里,但他们附加到输出。

为什么会这样?

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

int main(void){
        char input;
        char upper[100];
        int count = 0;

        while((input = getchar())){
                if(input == '\n')
                        break;
                if(input >= 'a' && input <= 'z')
                        input = toupper(input);
                *(upper + count) = input;
                count++;
        }

        printf("%s\n", upper);

        return 0;
}

3 个答案:

答案 0 :(得分:2)

您的代码对我有用。 唯一的,但是这是预期的,你在字符串之后得到垃圾,因为你的char数组的长度为100.你应该在字符串的末尾加一个0来告诉printf你的字符串在那里结束。把

*(upper + count) = 0;

在printf之前。

答案 1 :(得分:1)

您的代码存在一些问题:

  • 不会在字符串的末尾添加NULL终结符。
  • 没有检查索引超出已分配数组的范围。
  • 用户可以在没有换行符的情况下中断输入,使程序永远循环。
  • getchar返回一个int。

您可以尝试此修复:

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

const int MAX_CHAR = 101;

int main() {
    int input;
    char upper[MAX_CHAR];
    int count = 0;

    while( count < MAX_CHAR - 1 ) {
        input = getchar();
        if ( input == EOF  || input == '\n' ||  input == '\r' )
            break;
        if ( input >= 'a' && input <= 'z' )
            input = toupper(input);
        upper[count] = input;
        count++;
    }
    // add the null terminator
    upper[count] = '\0';

    printf("%s\n", upper);

    return 0;
}

答案 2 :(得分:0)

您可能希望将数组中的所有元素设置为0(ASCII NUL),因为我们不知道upper数组中的内容。

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

int main(void){
    char input;
    char upper[100];
    int count = 0;

    memset(upper, 0, 100);

    while((input = getchar())){
            if(input == '\n')
                    break;
            if(input >= 'a' && input <= 'z')
                    input = toupper(input);
            *(upper + count) = input;
            count++;
    }

    printf("%s\n", upper);

    return 0;
}

如果您不确定memset的作用,可以使用for循环来完成。

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

int main(void){
    char input;
    char upper[100];
    int count = 0;

    for (int i = 0; i < 100; i++) {
       upper[i] = 0;
    }

    while((input = getchar())){
            if(input == '\n')
                    break;
            if(input >= 'a' && input <= 'z')
                    input = toupper(input);
            *(upper + count) = input;
            count++;
    }

    printf("%s\n", upper);

    return 0;
}
相关问题