0

这是我的程序,将从标准输入中输入的所有字母大写。但是有些输出很奇怪。例如,如果输入是“lorem ipsum”,输出将是“LOREM IPSUMS?”。如果输入是单个字符,例如“m”,则输出将为“MZ#X?” . “S?” 和“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;
}
4

3 回答 3

2

你的代码对我有用。唯一的事情,但这是意料之中的,你会在字符串之后得到垃圾,因为你的 char 数组的长度为 100。你应该在字符串的末尾放一个 0 来告诉 printf 你的字符串在那里结束。放

*(upper + count) = 0;

就在 printf 之前。

于 2016-03-17T22:14:26.687 回答
1

您的代码有一些问题:

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

你可以试试这个修复:

#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;
}
于 2016-03-17T23:05:54.283 回答
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;
}
于 2016-03-17T22:11:30.167 回答