我需要从标准输入中逐行读取输入
但每行将包含 1 或 2 或 5 个字符串,例如:
bofob fbo
blabla bibi bobo fbo fbooo
bobobo bobo
bobof
我该怎么做?
我的想法真的看起来不专业而且行不通
char a[50],b[50],c[50],d[50],f[50];
int numOfStrings=0;
scanf(" %s",a); char a[50],b[50],c[50],d[50],f[50];
int numOfStrings=0;
scanf(" %s",a);
if (scanf (" %s",b)){
numOfStrings=2;
if (scanf (" %s %d %d",c,d,f)
numOfStrings=5;
}
if (scanf (" %s",b)){
numOfStrings=2;
if (scanf (" %s %d %d",c,d,f)
numOfStrings=5;
}
但它不起作用,因为它会从下一行读取输入
有没有办法读取整行(我知道它最多 250 个字符),然后知道其中有多少个单词?
编辑: 我会添加一个统计字数的功能 但是读一行直到结束行或 eof 最好的方式是什么??
int words(const char *sentence)
{
int count,i,len;
char lastC;
len=strlen(sentence);
if(len > 0)
{
lastC = sentence[0];
}
for(i=0; i<=len; i++)
{
if(sentence[i]==' ' && lastC != ' ')
{
count++;
}
lastC = int words(const char *sentence)
}
return count;
}
最佳答案
您需要使用fgets()
来逐行获取输入。检查手册页here 。它还将使您摆脱处理 [1/2/5/.....] number
空格分隔 字符串的限制。如果有足够的存储空间,您可以将 1 读取到任意
数量的“字符串”。
注意:您可能需要自己处理尾随换行符 \n
[由 ENTER 引起]。大多数时候都会造成麻烦。
关于c - 在c中读取1/2/5字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27060437/