如何来标记字符串在C的int数组? [英] how to tokenize string to array of int in c?

查看:233
本文介绍了如何来标记字符串在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

我想在我的计划是什么:

What I want in my program:

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.

推荐答案

以下code将一次读取文件中的行

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

您可以再tokenise输入使用的strtok()和 的sscanf()将文本转换数字。

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

从MSDN页面sscanf的:

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.

以下code将字符串转换为整数的数组。显然,对于一个可变长度的数组,你需要一个列表或者一些扫描输入两次,以确定真正解析它之前,数组的长度。

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

将允许输入到更加灵活。

will allow the input to be more flexible.

我不得不做一个搜索,提醒语法的自己 - 我发现它的在这里的MSDN

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

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