c - 使用 C 将文本文件中的内容扫描到 2 个数组中

标签 c parsing scanf

我在将这样的东西解析到数组中时遇到问题。

所以我的文本文件 test.txt 有这一行: (1231212A,1231212B)(1231212C,321128D)

我试图将其扫描到一个数组中,但它需要分成几部分

int 类型的第 1 部分应该是:123

第 2 部分:12

第 3 部分:12

第 4 部分(字符):A

我需要在该行内执行 4 次

这是我的代码,但它无法正常工作

{
int nums[1][12];
char chars[1][4];
FILE *file;

file = fopen("test.txt", "r");
if (file != NULL){

fscanf(file , "%*s%3d %2d %2d %s %*s %2d %2d %2d %s%*s        %*s%3d %2d %2d %s%*s %2d %2d %2d %s%*s" 
, &nums[0][0],&nums[0][1],&nums[0][2],&chars[0][0],&nums[0][3],&nums[0][4],&nums[0][5],&chars[0] 
[1],&nums[0][6],&nums[0][7],&nums[0][8],&chars[0][2],&nums[0][9],&chars[0][10],&nums[0][11],&chars[0] 
[3]);
}

当我打印这些数组时,它们没有打印正确的数字和字符。 我需要 fscanf 部分的帮助 谢谢您

最佳答案

使用 fgets() 从文件中读取后,使用 sscanf() 解析字符串包括“%n”来检测扫描了多少。

在格式中使用字符串文字连接也有帮助。

//                           v---not s
#define GROUP_FMT "%3d%2d%2d%c"

int n = 0;
sscanf(line, " (" GROUP_FMT " ," GROUP_FMT " ) (" GROUP_FMT " ," GROUP_FMT " ) %n",
  &nums[0][0], &nums[0][ 1], &nums[0][ 2], &chars[0][0], 
  &nums[0][3], &nums[0][ 4], &nums[0][ 5], &chars[0][1],
  &nums[0][6], &nums[0][ 7], &nums[0][ 8], &chars[0][2],
  &nums[0][9], &nums[0][10], &nums[0][11], &chars[0][3], &n);
// Did scanning reach the %n and was that the end of the string?
if (n && line[n] == '\0') Success();
else Fail();

关于c - 使用 C 将文本文件中的内容扫描到 2 个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312673/

相关文章:

java - 将 24 小时时间转换为分钟的简单日期格式

c - scanf 将字符转换为 int 而不进行转换

c - 如何在函数中将文本扫描为字符串?

c - 将 JPEG 屏幕截图保存为 C 中的 BYTE 缓冲区

c - C中文件的最大和最小数量

.net - 从包含字母和空格的字符串中解析整数 - C#

c - 接受用户输入并在整个过程中继续使用它的变量

c - 围栏密码算法c

通过网络复制符号链接(symbolic link)

swift - 解析project.pbxproj文件