2

こちらで質問するのは初めてなので、頑張ってみます。私は C が得意ではありません。中級 C プログラミングだけです。

ファイルを読み取るプログラムを作成しようとしていますが、これは機能しています。しかし、私は単語を検索してから、その単語を配列に保存しています。私が今行っていることは

for(x=0;x<=256;x++){
 fscanf(file,"input %s",insouts[x][0]);
 }

ファイルには、「input A0;」という行があります。「A0」をinsouts [x] [0]に保存したい。256 は、テキスト ファイルにいくつの入力があるか分からないので、私が選んだ数字です。

次のように宣言された insouts があります。

char * insouts[256][2];
4

3 に答える 3

0

fscanf を使用しようとするのではなく、';' を指定して "getdelim" を使用しないでください。区切り文字として。マニュアルページによると

" getdelim() は getline() と同様に機能しますが、改行以外の行区切り文字を delimiter 引数として指定できる点が異なります。getline() と同様に、ファイルの終わりの前に入力に区切り文字が存在しない場合、区切り文字は追加されません。到達しました。」

したがって、次のようなことができます(テストされておらず、コンパイルされていないコード)

char *line = NULL;
size_t n, read;
int alloc = 100;
int lc = 0;
char ** buff = calloc(alloc, sizeof(char *)); // since you don't know the file size have 100 buffer and realloc if you need more
FILE *fp = fopen("FILE TO BE READ ", "r");
int deli = (int)';';
while ((read = getline(&line, &n, fp)) != -1) {
   printf("%s", line); // This should have "input A0;" 
   // you can use either sscanf or strtok here and get A0 out 
   char *out = null ;
   sscanf(line, "input %s;", &out);
   if (lc > alloc) {
      alloc = alloc + 50;
      buff = (char **) realloc(buff, sizeof(char *) * alloc);
   }
   buff[lc++] = out
}

int i = 0 ; 
for (i = 0 ; i < lc; i++)
   printf ("%s\n", buff[i]);
于 2013-09-24T00:28:51.827 に答える
0

fgets()&を使用しsscanf()ます。I/O をフォーマット スキャンから分離します。

#define N (256)
char insouts[N][2+1]; // note: no  * and 2nd dimension is 3
for(size_t x = 0; x < N; x++){
   char buf[100];
   if (fgets(buf, sizeof buf, stdin) == NULL) {
     break;  // I/O error or EOF
   }
   int n = 0;
   //  2 this is the max length of characters for insouts[x].  A \0 is appended.
   //  [A-Za-z0-9]  this is the set of legitimate characters for insouts
   // %n record the offset of the scanning up to that point.
   int result = sscanf(buf, "input %2[A-Za-z0-9]; %n", insouts[x], &n);
   if ((result != 1) || (buf[n] != '\0')) {
      ; // format error
   }
}
于 2013-09-24T04:46:48.097 に答える