gpt4 book ai didi

c - 如何将字符串标记为 c 中的 int 数组?

转载 作者:太空狗 更新时间:2023-10-29 17:17:08 25 4
gpt4 key购买 nike

有人知道从文本文件中每行读取一个序列号并将其解析为 C 中的数组吗?

文件中的内容:

12 3 45 6 7 8
3 5 6 7
7 0 -1 4 5

我想要在我的程序中:

array1[] = {12, 3, 45, 6, 7, 8};
array2[] = {3, 5, 6, 7};
array3[] = {7, 0, -1, 4, 5};

我已经通过多种方式阅读它,但唯一的问题是只有当我想每行标记它时。谢谢。

最佳答案

下面的代码将一次读取一个文件一行

char line[80]
FILE* fp = fopen("data.txt","r");
while(fgets(line,1,fp) != null)
{
// do something
}
fclose(fp);

然后您可以使用 strtok() 对输入进行标记化和 sscanf()将文本转换为数字。

来自 sscanf 的 MSDN 页面:

Each of these functions [sscanf and swscanf] returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.

以下代码会将字符串转换为整数数组。显然,对于可变长度数组,您需要一个列表或对输入进行两次扫描以确定数组的长度,然后再实际解析它。

char tokenstring[] = "12 23 3 4 5";
char seps[] = " ";
char* token;
int var;
int input[5];
int i = 0;

token = strtok (tokenstring, seps);
while (token != NULL)
{
sscanf (token, "%d", &var);
input[i++] = var;

token = strtok (NULL, seps);
}

放置:

char seps[]   = " ,\t\n";

将使输入更加灵活。

我不得不进行搜索以提醒自己语法 - 我找到了 here in the MSDN

关于c - 如何将字符串标记为 c 中的 int 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1483206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com