如何读取未知长度的输入字符串? [英] How can I read an input string of unknown length?
本文介绍了如何读取未知长度的输入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我不知道这个词有多长,我就不会写char m[6];
,
这个词的长度可能是十或二十长.如何使用 scanf
从键盘获取输入?
If I don't know how long the word is, I cannot write char m[6];
,
The length of the word is maybe ten or twenty long.
How can I use scanf
to get input from the keyboard?
#include <stdio.h>
int main(void)
{
char m[6];
printf("please input a string with length=5
");
scanf("%s",&m);
printf("this is the string: %s
", m);
return 0;
}
请输入长度为5的字符串
你好
这是字符串:你好
please input a string with lenght=5
hello
this is the string: hello
推荐答案
动态保护区域时进入
例如
#include <stdio.h>
#include <stdlib.h>
char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(*str)*size);//size is start size
if(!str)return str;
while(EOF!=(ch=fgetc(fp)) && ch != '
'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(*str)*(size+=16));
if(!str)return str;
}
}
str[len++]=' ';
return realloc(str, sizeof(*str)*len);
}
int main(void){
char *m;
printf("input string : ");
m = inputString(stdin, 10);
printf("%s
", m);
free(m);
return 0;
}
这篇关于如何读取未知长度的输入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文