将文本文件中的每一列数据存储到C中的数组中
例如,我有一个文本文件名 file.txt,其中有 2 列数字,
10 1
20 2
30 3
40 4
50 5
我希望能够将数据列存储到数组中,以便我可以在其他地方使用这些数据。目前,使用底部的代码:
int main()
{
int i = 0, j = 0, numofProcesses = 0;
char *token;
// reading the textfile
char *filename = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: could not open file %s", filename);
return 1;
}
else
{
// reading line by line, max 256 bytes
const unsigned MAX_LENGTH = 256;
char SingleLine[MAX_LENGTH];
while (fgets(SingleLine, MAX_LENGTH, fp))
{
// num of Processes = count the number of line
numofProcesses += 1;
// print each line out
// printf("%s", SingleLine);
// remove trailing new line
SingleLine[strcspn(SingleLine, "\n")] = 0;
// print out each number in the text file base on the line
// Returns first token
token = strtok(SingleLine, " ");
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
// check number of processes
printf("\n\nNumber of process = %d", numofProcesses);
// close the file
fclose(fp);
}
printf("\n");
return 0;
}
我能够得到:
10
1
20
2
30
3
40
4
50
5
Number of process = 5
但是,我想要获得的输出存储在两个不同的数组中:
array a = [10, 20, 30, 40, 50]
array b = [1, 2, 3, 4, 5]
我可以知道是否有办法单独获取数组吗? 谢谢。
I have a text file name file.txt with 2 columns of number for example,
10 1
20 2
30 3
40 4
50 5
I want to be able to store the columns of data into an array so that I can use the data somewhere else. Currently, with the code at the bottom :
int main()
{
int i = 0, j = 0, numofProcesses = 0;
char *token;
// reading the textfile
char *filename = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: could not open file %s", filename);
return 1;
}
else
{
// reading line by line, max 256 bytes
const unsigned MAX_LENGTH = 256;
char SingleLine[MAX_LENGTH];
while (fgets(SingleLine, MAX_LENGTH, fp))
{
// num of Processes = count the number of line
numofProcesses += 1;
// print each line out
// printf("%s", SingleLine);
// remove trailing new line
SingleLine[strcspn(SingleLine, "\n")] = 0;
// print out each number in the text file base on the line
// Returns first token
token = strtok(SingleLine, " ");
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
// check number of processes
printf("\n\nNumber of process = %d", numofProcesses);
// close the file
fclose(fp);
}
printf("\n");
return 0;
}
I am able to get:
10
1
20
2
30
3
40
4
50
5
Number of process = 5
However, the output that I want to get is store in 2 different arrays:
array a = [10, 20, 30, 40, 50]
array b = [1, 2, 3, 4, 5]
May I know if there is anyway I can get the arrays separately?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。你可以做到的。我对您的代码做了一些更改(请参阅注释):
输出:
Yes. You can do it. I have made some changes in your code (see comments):
Output: