2016-11-02 23 views
0

私はfscanfをファイルから読み込み、これらの文字列を配列に入れようとしています。それは動作するようですが、私は私の配列に最後の文字列を取得しています。私はそれを印刷しようとすると、私は最後の文字列の文字だけを印刷しています。誰もが混乱した場合に備えて、fscanfが何をしても影響しないので、私の方法は含まれていませんでした。また、私のCMDLINEファイルには、次の文字列foo barr tar 526-4567 456-8792があります。fscanfを使用して文字列を配列に挿入する方法は?

出力は次のとおりです。

456-8792 
56-8792 
6-8792 

等...ここ

2 

はコードです:

int main (int argC, char *argV[]) { 
    FILE *fp; 
    int index; 
    int ret; 
    char str[1000]; 

    //Need at least 2 files to begin program 
    if (argC < 3) { 
     fprintf(stderr, "Usage: %s file\n", argV[0]); 
     exit(1); 
    }//if statemtn 

    //check to see if the CMDLINE file is in the arguements 
    ret = scanC(argC, argV); 

    //if no CMDLINE file is found, print error and exit 
    if (ret == 1) { 
     fprintf(stderr, "you must provide a CMDLINE file\n"); 
     exit(1); 
    } 

    //iterate and open CMDLINE file and read from it 
    for (index = 0; index < argC; index++) { 
     if (strcmp(argV[index], "CMDLINE") == 0) { 
      fp = fopen(argV[index], "r"); 
      //error check 
      if (fp == NULL) { 
       fprintf(stderr, "Counld not open file %s\n", argV[index]); 
       exit(1); 
      }//if statment 

      //read from fscanf and put it's arguements into an array 
      while (!feof(fp)) { 
       char *p2 = str; 
       //scan the strings of the file into str array 
       while (fscanf(fp, "%s", p2) != EOF) { 
        p2++; 
       }//while loop 2 
      }//while lop 1 

      //close the file for it is not needed to be open anymore 
      fclose(fp); 
     }//if statement 
    }//for looop 

    char *p; 
    p = str; 
    int j; 
    for (j = 0; j < strlen(str); j++) { 
     printf("%s\n", p); 
     p++; 
    } 
    return 1; 
} 
+2

[なぜwhile(!feof(file))が常に間違っているのですか?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong ) –

答えて

1

あなたは "現在の文字を" 設定するマーカーを使用することができます。

char *p2 = str; 
size_t k = 0; 
size_t pos = 0; 
//scan the strings of the file into str array at position pos 
while((k = fscanf(fp, "%s", p2 + pos)) != EOF){ 
    // update pos 
    pos += k; 
    p2++; 
}//while loop 2 

これは、ファイル全体を文字列に保存することを可能にします 1000文字未満です。 それ以外の場合は、whileループにセーフガードを追加してください。

2
char *p; 
p = str; 
int j; 
for (j = 0; j < strlen(str); j++) 
{ 
    printf("%s\n", p); 
    p++; 
} 

あなたはちょうどprintf("%s\n", str);は、代わりにあなたが異なるオフセットで始まる文字列と同じ文字列を印刷しているとして、それを印刷することができ、1つの文字列、たとえば"abcd"を、持っています。おそらく、あなたは十分な大きさの文字列の配列を割り当てることmallocreallocを使用して実際のアプリケーションでは、「文字列」と「文字列の配列」

//This will reserve 100 character arrays, or 100 strings 
char *arr[100]; 

int count = 0; 
while (fscanf(fp, "%999s", str) == 1) 
{ 
    arr[count] = malloc(strlen(str) + 1); 
    strcpy(arr[count], str); 
    count++; 
    if (count == 100) 
     break; 
} 

int i; 
for (i = 0; i < count; i++) 
    printf("%s\n", arr[i]); 

の間で混乱している

abcd 
bcd 
cd 
d 

を次のように結果がありますファイルを読む。

関連する問題