给定一个未知长度的用户输入(由最大长度为 100 的单词组成),有没有办法逐个字符串地动态读取它?
构建自己的函数,而不是 scanf 将有助于实现这一目标
注意:用户输入字符串end时停止输入。
#include <stdio.h> //the standard library file
#include <stdlib.h> //library file useful for dynamic allocation of memory
#include <string.h> //library file with functions useful to handle strings
//the function
char* scan(char *string)
{
int c; //as getchar() returns `int`
string = malloc(sizeof(char)); //allocating memory
string[0]='\0';
for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
{
string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
string[i] = (char) c; //type casting `int` to `char`
string[i+1] = '\0'; //inserting null character at the end
}
return string;
}
int main(void)
{
char *buf; //pointer to hold base address of string
while( strcmp((buf=scan(buf)),"end") ) //this loop will continue till you enter `end`
{
//do something with the string
free(buf); //don't forget to free the buf at the end of each iteration
}
free(buf); //freeing `buf` for last input i.e, `end`
}
让我们//do something with the string 看看上面的代码是否有效:)
我在 main 函数中更改了以下 while 循环:
while( strcmp((buf=scan(buf)),"end") )
{
//do something with the string
}
到
while( strcmp((buf=scan(buf)),"end") )
{
printf("you entered : %s\n",buf);
printf("size : %u\n",strlen(buf));
printf("reversing : %s\n",strrev(buf));
printf("\n-------------------\n");
free(buf);
}
现在,
输入:
hall
of
fame
stay in it
end
输出:
you entered : hall
size : 4
reversing : llah
-------------------
you entered : of
size : 2
reversing : fo
-------------------
you entered : fame
size : 4
reversing : emaf
-------------------
you entered : stay in it
size : 10
reversing : ti ni yats
-------------------