开发者

Putting strings into a 2D chararray in C

How do I put strings into an 2D char array from (for example) a file?

char buffert[10][30];
int i = 0;

while(!feof(somefile)) {
  fscan开发者_运维百科f(somefile, "%s", temp);
  buffert[i][] = temp;
  i++;
}

This will not do it.


Try this:

while(i < 10 && fscanf(somefile, "%29s%*[^ \t\n]", buffer[i]) != EOF) {
  i++;
}

The "%29s" format specifier reads up to 29 characters into buffer[i], which is all it has space for. The "%*[^ \t\n]" reads and throws away non-whitespace, in case the string was longer than 29 characters.

Additionally, while (!feof()) { } is almost always the wrong thing to do, because EOF isn't set on the stream until end of file is encountered.


Stolen from this forum:

#include <stdio.h>

main()
{
  int dirsize = 80;
  char array[9][dirsize];
  int linenum = 0;
  FILE *filepointer;
  filepointer = fopen("projectfile.txt","r");
  while (feof(filepointer) == 0)
  {
    linenum++;
    fgets(array[linenum], dirsize, filepointer);
  }
  fclose(filepointer);
} 

Another solution with a pointer to arrays instead of array of arrays is here.


it doesn't look to me like you're actually COPYING the string into an array. I'm surprised it compiles. am I missing something?

look into strcpy or strncpy, or you can copy using for loops.


Do away with the temp, and drop each string straight into the space you created for it (in buffert in this case).

char buffert[10][30];
int i = 0;
FILE * fp = fopen("myfile", "r");
while(!feof(fp)) { 
  fscanf(fp, "%s", buffert[i]);
  i++;
}

Here the file pointer is called fp. You will have to make a bunch of checks to prevent overflowing the 10 entries available in buffert, or the 30 chars available in each of its strings. You should also avoid feof().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜