简体   繁体   English

用文件io打印整行

[英]printing whole line with file io

This is a part of my 'Phonebook' program. 这是我的“电话簿”程序的一部分。

void viewall(){
    int n, checking = 0;
    char name[50];

    fp = fopen("Phonebook.txt","r");
    printf ("\n\n");

    fscanf (fp, "%s %d", name, &n);
    while (!feof(fp)){
        printf (" %s +880%d\n", name, n);
        fscanf (fp, "%s %d", name, &n);
        ++checking;
    }

    if (checking == 0){
        printf (" Contact List is Empty. No Contacts to Show...");
    }

    printf ("\n\n");
    fclose(fp);

    menu();
}

This part displays all the contacts in list. 此部分显示列表中的所有联系人。 But if any contact name has two parts they get separated. 但是,如果任何联系人姓名有两个部分,它们将被分开。 For example: I enter Anik Shahriar as name and then enter my number. 例如:我输入Anik Shahriar作为名称,然后输入我的电话号码。 I looked at my file and this data was there how it should be. 我查看了我的文件,并且该数据应有的状态。

Anik Shahriar 01*******93

But when I wanted to display all the contacts. 但是当我想显示所有联系人时。 It got printed like this: 它是这样打印的:

Anik 0
Shahriar 01*******93

How can i make the program print the whole line ? 如何使程序打印整行?

This behaviour is caused by the lines 此行为是由线条引起的

fscanf (fp, "%s %d", name, &n);

The format identifier %s scans for a single string. 格式标识符%s扫描单个字符串。 Any whitespace character ends the scan. 任何空白字符都会结束扫描。

http://www.cplusplus.com/reference/cstdio/scanf/ http://www.cplusplus.com/reference/cstdio/scanf/

%s %s
String of characters 字串
Any number of non-whitespace characters, stopping at the first whitespace character found. 任意数量的非空白字符,在找到的第一个空白字符处停止。 A terminating null character is automatically added at the end of the stored sequence. 在存储序列的末尾会自动添加一个终止的空字符。

I suggest to use ca CSV file and use a format string like. 我建议使用ca CSV文件并使用类似格式的字符串。

scanf("%[^,] %d", name, number)

Dont forget to test the scanf result value. 不要忘记测试scanf结果值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM