2014-11-21 64 views
-1

我需要由线读取在C 1/2/5串输入

从非标准输入线读取输入但每行包含1名或2或5的字符串等:

bofob fbo 
blabla bibi bobo fbo fbooo 
bobobo bobo 
bobof 

如何我可以这样做吗?

我的想法是真的不看profassional和不工作

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个字符),然后知道里面有多少个单词?

编辑: 我会添加一个计数字功能 但什么是最好的wat ro读一条线直到最后一行或者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; 
} 

回答

3

您需要使用fgets()采取输入行由行。检查手册页here。它也将解放你处理[1/2/5/.....] number s的空格分隔字符串的限制。提供足够的存储空间,您可以阅读1 to any“字符串”的数量。

注意:您可能需要自己照顾尾随换行\n [由输入]。大部分时间都会造成麻烦。

2

你可以扫描一条线,直到“\ n”与%[^\n],然后用strtok()行拆分成词:

#include <string.h> 
#include <stdio.h> 

const char s[2] = " "; 
const int MAX_LINE_SIZE = 128; 
FILE *fp; 
char *word, *str; 
int word_counter; 

/* Open the file here */  

while (fgets(str, MAX_LINE_SIZE, fp) != NULL) 
{ 
    word_counter = 0 
    /* get the first word */ 
    word = strtok(str, s); 

    /* walk through other words */ 
    while (word != NULL) 
    { 
     printf(" %s\n", word); 
     word_counter++; 

     word = strtok(NULL, s); 
    } 

    printf("This string contains %d words\n",word_counter); 

} 

/* END of FILE */ 
+0

我怎么知道我何时到达文件末尾? – JohnnyF 2014-11-21 11:45:13

+1

什么文件?你说你从标准输入 – 2014-11-21 11:45:56

+0

读取是的,但是如果我从标准输入发送一个文件,它将如何知道它完成没有/ n? – JohnnyF 2014-11-21 12:03:50

1

您可以使用fgets读取文件和strchr计数的空格数:

#include <stdio.h> 
#include <string.h> 

int main(void) 
{ 
    char s[250]; 
    char *p; 
    FILE *f; 
    int i; 

    f = fopen("demo.txt", "r"); 
    while ((p = fgets(s, sizeof s, f))) { 
     i = 0; 
     while ((p = strchr(p, ' '))) { 
      p++; 
      i++; 
     } 
     printf("%d spaces\n", i); 
    } 
    fclose(f); 
    return 0; 
}