Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从C语言的文本文件中读取带有空格字符的字符_C - Fatal编程技术网

从C语言的文本文件中读取带有空格字符的字符

从C语言的文本文件中读取带有空格字符的字符,c,C,我试着读文本文件看起来像 结果是:1020xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 但我希望它像照片一样。我哪里做错了?谢谢。fscanf()和%s将跳过空白字符。您应该使用fgets()来阅读整行内容 另外,您在(!feof(file))时使用,并且您应该在使用“读取”之前检查读取是否成功 另一个注意事项是,在if行中使用分号是错误的,因为

我试着读文本文件看起来像

结果是:1020xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

但我希望它像照片一样。我哪里做错了?谢谢。

fscanf()
%s
将跳过空白字符。您应该使用
fgets()
来阅读整行内容

另外,您在(!feof(file))时使用
,并且您应该在使用“读取”之前检查读取是否成功

另一个注意事项是,在
if
行中使用分号是错误的,因为它将禁用
NULL
检查,并在
fopen
失败时让它尝试从
NULL
读取内容

试试这个:

#include <stdio.h>

int main(void)
{
    FILE *file;

    char k[200][2];
    int i=0;

    if((file=fopen("blobs1.txt","r"))!=NULL)
    {
        
        while(fgets(k[i], sizeof(k[i]), file) != NULL)
        {
            printf("%s",k[i]);
            
        
        }
        
        fclose(file);
    }
}
#包括
内部主(空)
{
文件*文件;
chark[200][2];
int i=0;
如果((file=fopen(“blobs1.txt”,“r”)!=NULL)
{
while(fgets(k[i],sizeof(k[i]),file)!=NULL)
{
printf(“%s”,k[i]);
}
fclose(文件);
}
}

如果您确实需要scanf/fscanf,请尝试
“[^\n]”
而不是
“%s”
。它将一直读取到行终止符“\n”或文件结尾。

Your
fscanf(…,“%s”,…)
读取除spaces之外的所有内容您使用的
feof
不正确:这可能会有所帮助:您的代码似乎根本不关心换行符。似乎您只是想实现一个标准
,而((c=fgetc(f))!=EOF)putchar(c)一般规则:如果你是C语言的初学者(或中级,不管是什么意思),不要使用scanf。完全除非你有15年的语言经验,否则不要使用它。非常感谢,我很感激
#include <stdio.h>

int main(void)
{
    FILE *file;

    char k[200][2];
    int i=0;

    if((file=fopen("blobs1.txt","r"))!=NULL)
    {
        
        while(fgets(k[i], sizeof(k[i]), file) != NULL)
        {
            printf("%s",k[i]);
            
        
        }
        
        fclose(file);
    }
}