-4

我想通过指针将小写字母转换为大写字母。下面的代码不起作用,它会引发一些错误。

#include<stdio.h>

int main()
{
    char somearray[10]; char mask;
    mask = 1 << 5;
    mask = ~mask;
    char *someptr;
    gets(somearray);
    puts(somearray);
    someptr =&somearray[0];

    while (*someptr != '\n')
    {
        *someptr = *someptr & mask ;

        someptr++;
    }
    printf("%s",someptr);
    return 0;
} 

得到一个错误:

not able to compile , if compiled runtime error

即使下面的代码也不起作用:

#include <stdio.h>

int main()
{
    char somearray[10];
    char mask;
    char *someptr;

    mask = 1 << 5;
    mask = ~mask;

    fgets( somearray, sizeof(somearray), stdin ); /* gets() is suspect: see other reactions */
    puts(somearray);
    for ( someptr = somearray; *someptr != '\0';someptr++)
    {
        *someptr &= mask ;
    }

    printf("%s",someptr);



    return 0;
}

输入:abcd 输出:abcd.,预期:ABCD

4

3 回答 3

3

gets()不会将换行符存储在数组中,因此循环将超出数组的末尾并访问和修改它不应该的内存。使用scanf()并限制读取的字符数以防止缓冲区溢出(如果真的 C++ 使用std::getline()and std::string):

scanf("%9s", somearray);

并在第一个空字符处终止循环:

while (*someptr != '\0')

您将希望传递somearrayprintf()循环之后,因为someptr将指向结尾somearray并且只打印一个空字符串。


值得一读:警告:gets 函数很危险

于 2012-07-12T21:51:27.197 回答
0

一些指示:

改用 fgets 从 keybaord 读取,这样您就可以指定不超过缓冲区的字符串的最大大小

例如fgets( somearray, sizeof(somearray), stdin );

改用标准函数 tolower(int c)

例如*someptr = tolower(*someptr);

在你的while循环中检查字符串的结尾,即while (someptr && someptr!='\n') 他们的循环处理从fgets和scanf返回的字符串的方式

于 2012-07-12T22:13:51.767 回答
-1

我清理了一下代码,但我仍然不明白它的意图

#include <stdio.h>

int main()
{
    char somearray[10]; 
    char mask;
    char *someptr;

    mask = 1 << 5;
    mask = ~mask;

    gets(somearray); /* gets() is suspect: see other reactions */
    puts(somearray);
    for ( someptr = somearray; *someptr != '\n';someptr++) 
    {
        *someptr &= mask ;
    }

    printf("%s",someptr); /* must point to '\n', otherwise we would 
                          ** not get here BTW: gets() removes the \n 
                          ** and replaces it by a \0 so we wont get here
                          */
    return 0;
}

顺便说一句:如果你想向人类读者展示你的意图:当文字就足够时不要使用变量:

*someptr &= ~(0x20);

但是,更好的是:

 *someptr = toupper (*someptr);
于 2012-07-12T22:23:51.597 回答