从文件中扫描字符串,忽略最后一个字符

时间:2014-05-15 17:49:02

标签: c string scanf

编辑:糟糕,忘了说这是C

我有一个.txt文件,其中包含以下内容:

    blabla, 213, 32

我想将第一个字符串存储在变量中,所以我这样做:

    char x[6];
    int y, z;
    fscanf(finput, "%s, %d, %d", x, y, z)

但是当我打印" x"我明白了:

    blabla,

并且文本的其余部分无法正确存储。

我觉得最奇怪的是我的数组x具有相同数量的"空格"因为blabla有字符,但它仍然存储七个字符。

解决方法是读取每个字符并单独存储它们,但如果可能的话,我想将其作为字符串。

2 个答案:

答案 0 :(得分:2)

首先,这一行

fscanf(finput, "%s, %d, %d", x, y, z)
应修复

以消除未定义的行为:

fscanf(finput, "%s, %d, %d", x, &y, &z)
//                              ^   ^
//                              |   |
// You need to take an address of int variables

如果您不希望逗号包含在字符串中,请改用%[^,]

fscanf(finput, "%5[^,], %d, %d", x, &y, &z)
//                ^^^^
//                 ||
// This means "read characters until you hit a comma

请注意,我添加了5以将正在读取的字符串的长度限制为六个char

最后,看看fscanf是否返回了适当数量的项目,获取其返回值,并检查它是否等于您预期的项目数量:

int count = fscanf(finput, "%5[^,], %d, %d", x, &y, &z);
if (count == 3) {
    // All three items are there
} else {
    // We did not get enough items
}

答案 1 :(得分:0)

x是一个包含6个字符的数组。您不能在静态分配的数组上存储更多内容。