获取数组中每个元素的索引

Get an index of every element in an array

本文关键字:元素 索引 数组 获取      更新时间:2023-10-16
使用

C++,我使用 fgets 将文本文件读入 char 数组,现在我想获取该数组中每个元素的索引.即 line[0]= 0.54 3.25 1.27 9.85,然后我想返回一个单独数组中 line[0] 的每个元素,即 readElement[0] = 0.54。我的文本.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 linen",line[0]); // this generates an error
readElement [n]= strtok(line, " "); // Splits spaces between words in line
    while (readElement [1] != NULL)
  {
printf ("%sn", readElement [1]); // this print the entire line not only element 1
  readElement [1] = strtok (NULL, " ");
  }
n++;
}

谢谢

readElement看起来声明错误。 只需将其声明为指向字符串开头的指针:

char* readElement = NULL;

您也没有检查来自 fopen 的返回值。 这是最有可能的问题。 因此,如果文件实际上没有打开,则当您将其传递给 printf 时,"line"就是垃圾。

如果你真的想将行的每个元素存储到一个数组中,你需要为它分配内存。

另外,不要将变量命名为"read"。 "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 linen", line);
        readElement = strtok(line, " ");
        while (readElement != NULL)
        {
             printf ("%sn", readElement);
             readElement = strtok (NULL, " ");    
        }
      }
    }
    fclose(filestream);
}