2013-03-27 97 views
0

我有一個名爲commands.txt的文本文件,其中包含一些命令後跟一些參數。 例子:如何通過數字從字符串中分離單詞C

STOP 1 2 4 
START 5 2 1 8 
MOVE 
CUT 0 9 

我想從這個文本文件中讀取每一行,並打印這樣的事情

STOP: 1 2 3 
START: 5 2 1 8 
MOVE: 
CUT: 0 9 

我讀用於fgets每一行,然後我試着用sscanf的但不工作。

char line[100] // here I put the line 
char command[20] // here I put the command 
args[10]   // here I put the arguments 



#include<stdio.h> 
    int main() 
    { 
    FILE *f; 
char line[100]; 
char command[20]; 
int args[10]; 

f=fopen("commands.txt" ,"rt"); 
while(!feof(f)) 
{ 
fgets(line , 40 , f); 
//here i need help 
} 
fclose(f); 
return 0; 
} 

你能幫幫我嗎?

+0

爲了上帝的愛,請避免'sscanf()'及其任何變體!他們確實做的唯一事情就是導致更大的混亂。 – 2013-03-27 21:42:46

+0

任何人都可以幫助我嗎? – Alex 2013-03-27 22:31:07

+0

這裏有一個提示 - 一次一個字符地走過「行」。如果它不是空間,輸出它。如果是空格,輸出':',然後輸出空格。之後,只需輸出所有其他角色而不看它們。 – twalberg 2013-06-13 22:12:24

回答

0

我認爲你會以錯誤的方式去解決整個問題。如果你想收集與參數分開的命令來做些什麼,那麼你需要使用ctype.h進行測試。

但是,對於您想要執行輸出的方式,您並不需要保存所有這些緩衝區。只需打印整個東西,在你需要的地方填寫你的冒號。

#include <stdio.h> 
    #include <stdlib.h> 
    #include <ctype.h> 

    int main(){ 

     FILE *f; 
     char *buf; 
     buf = NULL; 
     int i = 0, size; 

     f=fopen("commands.txt", "r"); 
     fseek(f, 0, SEEK_END); 
     size = ftell(f); 
     fseek(f, 0, SEEK_SET); 
     buf = malloc(size + 1); 
     fread(buf, 1, size, f); 
     fclose(f); 

     for(i = 0; i < size ; i++){ 
     while(isalpha(buf[i])){ 
      printf("%c", buf[i++]); 
     } 
     printf(":"); 
     while(buf[i] == ' ' || isdigit(buf[i])){ 
      printf("%c", buf[i++]); 
     } 
     printf("\n"); 
     } 
    return 0; 
    } 
相關問題