Как добавить несколько строк с пробелами в c? - PullRequest
0 голосов
/ 22 января 2020

Я пытаюсь сохранить несколько строк с пробелами в массиве.

#include<stdio.h>
#define L 30

void main(){

    puts("\t+----------------------+\n\t| Contacts Application |\n\t+----------------------+\n");

    int noc; // number of contacts

    printf(" How many contacts do you want to store: ");
    scanf("%d", &noc);

    char name[noc][L];
        int  number[noc];
        int  a, b; // for counters in loop in switch

    if(noc>0){

        for(int i = 0; i < noc; i++){
            printf("\n\tName %d: ", i+1);
            //scanf("%s", &name[i]);
            fgets(name[i], L, stdin);

            printf("\tNumber: ");
            scanf("%d", &number[i]);
        }

        /** This will clear the screen **/
        #ifdef _WIN64
         system("cls");
        #elif __linux__
         system("clear");
        #endif

        puts("\n\tAll contacts have been saved successfully.\n");
        puts("\t1. Show all the contacts.");
        puts("\t2. Search any contact.\n");

        int choice;
        printf("\tEnter your choice: ");
        scanf("%d", &choice);

        switch(choice){
            case 1:

             for(int a = 0; a < noc; a++){
                printf("\n\t %d: %s - %d", a+1, name[a], number[a]);
             }

             break;

            case 2:
             //searchContact();

            default:
             puts("\n\tInvalid option, please try again.\n");
        }

    } else{
        puts("\nPlease enter more than zero.");
    }
} // main function

И этот код не работает, не знаю почему, @kutt в комментариях добавил пример, который работает, но это не так, почему?

Что можно сделать, чтобы решить проблему, поскольку выполнение напрямую передается функции & number scanf ().

1 Ответ

1 голос
/ 22 января 2020

Вам не нужно использовать fgets, если вы добавляете пробел перед %d и %[^\n]. Вам также следует проверить возвращаемое значение scanf, чтобы проверить, была ли операция успешной.

Вот фиксированный код.

Если этот код, я повторяю запрос на число, если входное значение не является числом.

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

void main(){

    puts("\t+----------------------+\n\t| Contacts Application |\n\t+----------------------+\n");
    int noc; // number of contacts
    int cnt;
    do {
        printf(" How many contacts do you want to store: ");
        cnt = scanf("%d", &noc);
    } while (cnt != 1);


    if(noc>0){
        char name[noc][30];
        int  number[noc];
        int  a, b; // for counters in loop in switch

        for(int i = 0; i < noc; i++){
            printf("\n\tName %d: ", i+1);
            scanf(" %[^\n]", &name[i]);

            do {
                printf("\tNumber: ");
                cnt = scanf(" %d", &number[i]);
            } while (cnt != 1);
        }

        /** This will clear the screen **/
        #ifdef _WIN64
         system("cls");
        #elif __linux__
         system("clear");
        #endif

        puts("\n\tAll contacts have been saved successfully.\n");
        puts("\t1. Show all the contacts.");
        puts("\t2. Search any contact.\n");

        int choice;
        printf("\tEnter your choice: ");
        scanf("%d", &choice);

        switch(choice){
            case 1:

             for(int a = 0; a < noc; a++){
                printf("\n\t %d: %s - %d", a+1, name[a], number[a]);
             }

             break;

            case 2:
             //searchContact();

            default:
             puts("\n\tInvalid option, please try again.\n");
        }

    } else{
        puts("\nPlease enter more than zero.");
    }
} // main function
...