如何使用 C 中的符号分隔的 sscanf 读取整数?

How to read integers with sscanf separated by symbols in C?

所以我有一个具有以下值的字符串

[7, 8]

现在我不想将每个值(仅数字)存储在二维数组中 [1][2]。
我很确定使用 sscanf 是执行此操作的最佳方法,但我如何告诉 sccanf 只读取整数?

提前致谢

sscanf("[%d,%d]", Array[a][b], Array[c][d]);

如果您的系统没有 getline.

,您可能会使用 getline(3), or fgets(3) 得到一整行

然后你可以parse that line manually. You might indeed at some point use sscanf(3) (and you could use %n and always test the return count from sscanf), but you could use strtol(3)(它的endptr参数很方便!),等等

始终 测试 sscanffscanfscanf 给出的 return 计数!

有些人可能会推荐 strtok(3),我不喜欢它,因为它是有状态且不可重入的。

顺便说一句,二维数组在 C 中很棘手(我建议避免使用它们并仅使用一维数组)。你可能 dynamically allocate some struct (that you previously declare) ending with a flexible array member.

如果我理解你的问题,我不会。但是我试过了。

快n脏。也许这有帮助。

for(int i =1; i++; i =< (sizeof(array1D)/arraydatatype) )
{
 array2D[i-1][i-1] = array1D[i-1];
 array2D[i-1][i-1] = array1D[i];
}

i = 0;
j = 0;
while (i < arraysize)
{ array2D [j][0] = array1D [i];
 array2D [j][1] = array1D [i+1];

 j++;
 i+=2; 
}

scanf 仅用于从控制台读取。但是你已经有一个数组了?!如果你有一个字符串,你可以使用 strncpy 或其他东西..