我正在尝试制作一个程序,用户输入一个字符串,然后如果他们想输入他们想要替换的字母以及用什么替换。我想使用 malloc 来设置数组,但是如何使用 scanf 来设置数组?
请有人帮忙。
谢谢!
这是程序在进入替换方法之前的样子:
char *s,x,y;
printf("Please enter String \n");
scanf("%s ", malloc(s));
printf("Please enter the character you want to replace\n");
scanf("%c ", &x);
printf("Please enter replacment \n");
scanf("%c ", &y);
prinf("%s",s);
最佳答案
您无法事先知道用户输入的大小,因此如果用户输入尚未结束,您需要动态分配更多内存。
一个例子是:
//don't forget to free() the result when done!
char *read_with_alloc(FILE *f) {
size_t bufsize = 8;
char *buf = (char *) malloc(bufsize);
size_t pos = 0;
while (1) {
int c = fgetc(f);
//read until EOF, 0 or newline is read
if (c < 0 or c == '\0' or c == '\n') {
buf[pos] = '\0';
return buf;
}
buf[pos++] = (char) c;
//enlarge buf to hold whole string
if (pos == bufsize) {
bufsize *= 2;
buf = (char *) realloc((void *) buf, bufsize);
}
}
}
一个实用的替代解决方案是限制 buf 大小(例如,限制为 256 个字符),并确保只读取该数量的字节:
char buf[256]; //alternative: char *buf = malloc(256), make sure you understand the precise difference between these two!
if (scanf("%255s", buf) != 1) {
//something went wrong! your error handling here.
}
关于c - 使用用户输入进行 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784524/