首页 > 解决方案 > C:使用 scanf() 输入未知大小

问题描述

我正在尝试制作一个简单的程序,您可以在其中放入一些文本,然后它会写回您刚刚写的内容。

例如,如果我写“Hello World”,程序应该写回“Hello World”

我认为它应该如何工作是这样的:

loop to check if the current character is '\0'

if not print the current character and reallocate 1 more byte of memory

else stop the loop

所以这看起来很容易,但我的尝试无法正常工作,例如,如果你只输入几个字符,它会毫无问题地回信给你,但字符串更长..它根本不工作。

我知道使用 fgets() 是可能的,但我想了解为什么我的带有 scanf() 的版本不起作用。

(我的代码)

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int mem = 2;
    char * str = malloc(mem);

    scanf("%s", str);

    while (*str != '\0') {
        printf("%c", *str);
        realloc(str, mem++);
        str++;
    }

    free(str);

    return 0;
} 

编辑:我以为我只是犯了一个小错误,但是在阅读了评论之后,看起来我在这个小程序中做错了很多事情。我将确保我更好地理解 C 是如何工作的,并在以后重试这个程序。谢谢您的帮助!

标签: cscanf

解决方案


你的程序可以更简单

#include <stdio.h>

int main() {

    char c;
    
    while( scanf("%c", &c) == 1 ) {
        
        printf("%c", c);
    }
    
    return 0;
}

推荐阅读