c - 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 是如何工作的,并在以后重试这个程序。谢谢您的帮助!
解决方案
你的程序可以更简单
#include <stdio.h>
int main() {
char c;
while( scanf("%c", &c) == 1 ) {
printf("%c", c);
}
return 0;
}
推荐阅读
- javascript - 如何创建一个“处理”多个文本字段以及字符计数器文本字段的处理函数
- reactjs - 如何在反应中应用链接中的活动菜单?
- javascript - 在使用 Firebase 注册时上传图片
- python - Pyqt将插槽连接到具有默认参数的函数而没有lambda
- scala - 根据另一个数据框的行值在数据框中添加新列
- javascript - 使用 jest 模拟进度条
- powershell - 尝试使用 Powershell 中的参数运行可执行文件
- python-3.x - 根据输入整数查找 Python 列表的子集列表
- javascript - html视频键控制和格式化
- azure-cosmosdb - 无法在 Cosmos DB 中获取按值排序的前 n 条记录