获取数组中每个元素的索引
Get an index of every element in an array
使用
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);
}
相关文章:
- 在对向量中查找元素的索引
- 当该数组的索引中没有元素时,指针指向什么?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 如何在C++中递归地找到max元素的索引?
- 编译器(Visual C++)如何优化按索引访问矢量元素?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用推力根据索引更改某些元素的值
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- CPtrList - 如何获取元素的索引?
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 矢量指针索引处的读取元素
- C++函数返回两个 char 数组的相同索引元素
- 特征:类似 numpy 的元素索引
- 如何在另一个数组中找到一个未排序数组的不同元素索引?
- C 无法使用嵌套环将数组的元素索引
- Opencv Mat的元素索引产生垃圾
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 按内容访问QVector元素索引
- C++ 矢量元素索引