c - 如何将字符串标记为c中的int数组? [英] how to tokenize string to array of int in c?

查看:43
本文介绍了c - 如何将字符串标记为c中的int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Anyone got anything about reading a sequential number from text file per line and parsing it to an array in 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};

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

I've been through several ways to read it, but the only matter is only when i want to tokenize it per line. Thank you.

推荐答案

以下代码一次读取一个文件一行

The following code will read a file a line at a time

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

然后您可以使用 strtok()sscanf() 将文本转换为数字.

You can then tokenise the input using strtok() and sscanf() to convert the text to numbers.

来自 sscanf 的 MSDN 页面:

From the MSDN page for sscanf:

这些函数 [sscanf 和 swscanf] 中的每一个都返回成功的字段数转换和分配;回报值不包括字段已阅读但未分配.回报值为 0 表示没有字段被分配.返回值为EOF对于错误或如果结束在第一个之前到达字符串转换.

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.

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

The following code will convert the string to an array of integers. Obviously for a variable length array you'll need a list or some scanning the input twice to determine the length of the array before actually parsing it.

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";

将使输入更加灵活.

我不得不进行搜索以提醒自己语法 - 我找到了它这里在 MSDN

这篇关于c - 如何将字符串标记为c中的int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆