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

标签 c arrays numbers

有人知道从文本文件中每行读取一个序列号并将其解析为 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/

相关文章:

c - HM-10 和 Arduino - 发送没有代码行结尾的 AT 命令

java - Point[] 数组在尝试设置变量时抛出 NullPointerException

在 c 中,cast 指定二维数组的数组类型错误

Javascript如何知道一个数组是否是另一个数组的子数组

php - 在 PHP 中将字符串 [基本上是逗号分隔的数字] 转换为整数的最佳方法

algorithm - 从两个值生成唯一 ID

c++ - 从控制台读取字符

c - 我应该使用什么哈希从一组字符串中生成随机值

我的二进制程序中的 java.lang.NumberFormatException

c - 从文件扫描