【问题标题】:C scanf() does not read full lineC scanf() 不读取整行
【发布时间】:2021-12-06 10:33:31
【问题描述】:

我想为家庭作业创建文本清理器,但是当我使用地址清理器启动程序时,即使我使用 free(),我也会遇到 heap-buffer-overflow 异常。

预期输出:

he3llo world
helloworld

实际输出:

he3llo world
hello

提前感谢您的任何回答!

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char* fix_text(char* data, int len)
{
    char* fixed_message = malloc (len * sizeof(char));
    int offset = 0; //used for correct parse
    for (int i = 0; i < len; i++)
    {
        
        if (isalpha(data[i]))
        {
            
            fixed_message[offset] = data[i];
            offset++; 
        }
        
        else if(data[i] == '\0')
        {
            break;
        }
        else if(data[i] == ' ')
        {
            continue;
        }
    }
    return fixed_message;
}
int main()
{
    char * text = malloc(100 * sizeof(char));
    scanf("%s", text);
    char* result = fix_text(text, 100);
    printf("%s\n", result);
    free(text);
    free(result);
    return 0;
}

【问题讨论】:

  • 你应该用 \0 结束你的字符串,因为现在你只是中断但没有正确结束字符串。也不需要继续的第三种情况

标签: c scanf


【解决方案1】:

您的代码仅输出hello 的问题与循环停止无关。这是因为您的scanf 只读取到空格。所以你传递给你的函数的字符串text基本上只有hello。 你可以通过使用来解决这个问题

scanf("%[^\n]s",text);

阅读直到换行。有关更多详细信息,您可以查看 this question

正如@Jabberwocky 指出的那样,您并没有终止您的固定消息。当您在原始消息中遇到相同的问题时,您可以在固定消息的末尾添加空终止符 \0 而不仅仅是中断

else if(data[i] == '\0')
{
    fixed_message[offset] = data[i];
    break;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多