为什么不打印连字符( - )?

时间:2017-10-10 08:12:48

标签: c scanf

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[])
{
        FILE* fp = fopen(argv[1],"r");
        char* ptr;
        int size;
        while(1){
                int scanfinteger = fscanf(fp,"%d",&size);
                ptr = (char*)malloc((size+1)*sizeof(char));
                if(scanfinteger != 1){
                        int result = fscanf(fp,"%s",ptr);

                        printf("ptr:[%s]\n",ptr);
                        if(result == EOF)
                                break;
                }
        }
        return 0;

}

input_file(argv [1])包含此

10 This
10 is
10 buffers
10 -
10 hi
10     -hello

我的节目输出

ptr: [This]
ptr: [is]
ptr: [buffers]
ptr: [10]
ptr: [hi]
ptr: [hello]

我无法理解连字符被消耗的原因。有人见过这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:3)

如果我建议使用其他解决方案,我建议您阅读,然后解析这些行。

也许是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char* argv[])
{
    // First make sure you have enough arguments
    if (argc < 2)
    {
        printf("Need an argument!\n");
        return 1;
    }

    // Open the file, and make sure we succeeded
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL)
    {
        printf("Failed to open the file %s: %s\n", argv[1], strerror(errno));
        return 1;
    }

    // Now read the file, one line at a time
    char line[100];
    while (fgets(line, sizeof line, fp) != NULL)
    {
        // Now we have a line, attempt to parse it
        int value;
        char string[100];
        if (sscanf(line, "%d %99s", &value, string) != 2)
        {
            printf("Failed to parse the current line\n");
            break;  // Break out of the loop
        }

        printf("Read value %d, string '%s'\n", value, string);
    }

    // All done, or we had an error (should probably check that)
    // Anyway, close the file and end the program
    fclose(fp);
}

当前代码的问题(似乎不是您运行的实际代码)是,如果读取数字失败,则只读取字符串

我不知道你的实际代码产生了什么问题。但不知怎的,它不同步。这可以看出,你用一行读取数字作为字符串。