Can't make a proper acquisition loop - C

67 views Asked by At

what I'm trying to do is create a loop that collects a string (in this case a name) and then questions the user through the request of a character whether he wants to keep inserting more.

#include <stdio.h>
#include <string.h>
void main(){
    char c, str[5][20];
    int i=0;
    do {
        printf("What's your name?\n");
        gets(str[i]);
        i++;
        printf("Do you want to insert more?\n");
        scanf("%c\n",&c);
    } while (c=='y');
}

The number of strings that I read and their lenght are arbitrary and not what I'm having trouble with, was just wondering if there was a "correct way" of using this kind of acquisition or if I should give up on it.

2

There are 2 answers

1
Krapp Automation On

This becomes easier, when turning it around: instead of asking for more, wait for empty input

#include <stdio.h>
#include <string.h>
void main(){
        char c, str[5][20];
        int i=0;
        do {
            printf("What's your name?  - (end list with empty string)\n");
            gets(str[i]);
            i++;
        } while (len(str[i-1] > 0) && (i < 5));
    }
2
Niklas Rosencrantz On

You could do it this way.

#include <stdio.h>
#include <string.h>

int main() {
    char c[3], str[5][20];
    int i = 0;
    do {
        printf("What's your name?\n");
        if (fgets(str[i], sizeof str[i], stdin)) {
            // input has worked, do something with data
            i++;
        }
        printf("Do you want to insert more?\n");
        if (fgets(c, 3, stdin)) {
            // input has worked, do something with data
        }
    } while (c[0] == 'y');
}

Test

What's your name?
Mallory
Do you want to insert more?
y
What's your name?
Carol
Do you want to insert more?
no

Process finished with exit code 0