【问题标题】:Writing in binary files C programming with spaces用空格编写二进制文件 C 编程
【发布时间】:2017-10-20 09:55:33
【问题描述】:

我想在二进制文件的一行上写三个名字。这个怎么做?例如: 伊万·彼得罗夫 彼得罗夫。 如果我写

char name[50];
int sizeName;
FILE*fp;
    if((fp=fopen("clients.bin","ab+"))==NULL)
    {
        printf("Error opening the file\n");
        exit(1);
    }
    printf("Enter client's name: \n");
    scanf("%s",name);
sizeName=strlen(name);
fwrite(&sizeName,sizeof(int),1,fp);
fwrite(name,sizeName,1,fp);

这样我只能在文件中写 Ivan,但我想要所有 3 个字?怎么办@

【问题讨论】:

  • scanf() 接受输入,直到遇到空格。对于带空格的字符串,使用fgets() 读取。
  • 使用fgets(name, sizeof name, stdin);scanf("%49[^\n]%*c", name);

标签: c string file io whitespace


【解决方案1】:

问题在于您读取输入的方式。 scanf() 一遇到空格就会停止。因此name 将只存储“Ivan”。 fgets() 可以在这里派上用场。

改变这个:

scanf("%s",name);

到这里:

fgets(name, sizeof(name), stdin); // read the line (including the newline from the user's enter hit
name[strlen(name) - 1] = '\0';    // overwrite the newline

你应该得到这个:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
Enter client's name: 
Ivan Petrov Petrov
Ivan Petrov Petrov

在像这样printf("%s\n", name); 打印你的字符串之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多