[英]How to read each line into an integer array, from a file in C?
How do I read each line of a file opened in my C program to an integer array. 如何将在C程序中打开的文件的每一行读取为整数数组。 I cannot use fgets
and sscanf
as the input is not known beforehand. 我不能使用fgets
和sscanf
因为事先不知道输入。 The length of each row and the number of columns can vary. 每行的长度和列数可以变化。
Tried fscanf
, fgetc
, and others, but they seem to run into problems while detecting the newline. 尝试了fscanf
, fgetc
和其他人,但他们似乎在检测换行时遇到了问题。 And I ended up reading the entire file together, instead of into different arrays. 我最终一起读取整个文件,而不是读到不同的数组。
eg, the file contains: 例如,该文件包含:
1 2 3 4 5
1 2 3
2 3 4
This should be stored in arr1[] = {1,2,3,4,5} , arr2[] = {1,2,3} , arr3[] = {2,3,4}
这应该存储在arr1[] = {1,2,3,4,5} , arr2[] = {1,2,3} , arr3[] = {2,3,4}
Feed characters into a per-line buffer. 将字符输入每行缓冲区。 Upon end-of-line (ie, when you hit a newline character \\n
), tokenize the buffer with strtok
or similar. 在行结束时(即,当你点击换行符\\n
),用strtok
或类似标记缓冲区。 Read the tokens into a pre-allocated or resizable array or struct
of your choice. 将标记读入预先分配或可调整大小的数组或struct
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.