2014-11-21 46 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; 
}