使用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++;
}
感谢
的另一种方法[如何把输入字符串从标准输入输出到载体中,每个容器中的一个字(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
你说你用C++编码,但是我看到的只是C. 听起来你的文本文件在每一行上有多个值。 你有没有考虑过使用二维数组? – 2012-04-22 06:42:39