2012-04-22 132 views
-1

使用C++,我正在使用fgets将文本文件读入char数组,现在我想要获取此数组中每个元素的索引.i.e。 line [0] = 0.54 3.25 1.27 9.85,那么我想在单独的数组中返回行[0]的每个元素,即readElement [0] = 0.54。 我的text.txt文件的格式为:0.54 3.25 1.27 9.85 1.23 4.75 2.91 3.23 这里是我写的代码:获取数组中每个元素的索引

char line[200]; /* declare a char array */ 
char* readElement []; 

read = fopen("text.txt", "r"); 
while (fgets(line,200,read)!=NULL){ /* reads one line at a time*/ 
printf ("%s print line\n",line[0]); // this generates an error 

readElement [n]= strtok(line, " "); // Splits spaces between words in line 
    while (readElement [1] != NULL) 
    { 
printf ("%s\n", readElement [1]); // this print the entire line not only element 1 

    readElement [1] = strtok (NULL, " "); 
    } 
n++; 
} 

感谢

+0

的另一种方法[如何把输入字符串从标准输入输出到载体中,每个容器中的一个字(http://stackoverflow.com/questions/8062545/c-how-to-put-an- input-string-from-stdio-into-a-vector-one-word-per-container) – 2012-04-22 06:29:58

+0

你说你用C++编码,但是我看到的只是C. 听起来你的文本文件在每一行上有多个值。 你有没有考虑过使用二维数组? – 2012-04-22 06:42:39

回答

0

readElement看起来误报的。只要将它声明为指向字符串开头的指针即可:

char* readElement = NULL; 

您不检查fopen的返回值。这是最可能的问题。因此,如果文件没有真正打开,那么当你将它传递给printf时,“行”就是垃圾。

而且,如果您实际上想将行的每个元素存储到数组中,则需要为其分配内存。

另外,不要将变量命名为“read”。 “读取”也是较低级别函数的名称。

const size_t LINE_SIZE = 200; 
char line[LINE_SIZE]; 
char* readElement = NULL; 
FILE* filestream = NULL; 

filestream = fopen("text.txt", "r"); 
if (filestream != NULL) 
{ 
    while (fgets(line,LINE_SIZE,filestream) != NULL) 
    { 
     printf ("%s print line\n", line); 

     readElement = strtok(line, " "); 
     while (readElement != NULL) 
     { 
      printf ("%s\n", readElement); 
      readElement = strtok (NULL, " ");  
     } 
     } 
    } 
    fclose(filestream); 
} 
+0

感谢selbie给你快速回复,但我想将文本文件的每一行存储在一个数组中,然后在程序中稍后使用每个元素。即我想读取这行行[0] = 0.54 3.25 1.27 9.85,然后使用readElement [0] = 0.54提取此数组的一个元素。如何实现这一目标?干杯 – user999 2012-04-22 07:12:56

+0

你首先需要计算行数中有多少个元素(数字),然后分配一个适当大小的数组来保存每个元素(数字)。然后,数组中的每个元素都应该具有适当的大小以保存每个字符串。 – selbie 2012-04-22 17:35:58