0

I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:

#include <stdio.h>

int main()
{
    char continued;
    int i = 0;
    char instrType[10];
    int time[10];

    printf("\nL-lock a resource");
    printf("\nU-unlock a resource");
    printf("\nC-compute");
    printf("\nPlease Enter The Instruction Type");
    printf(" and Time Input:");
    scanf("%c", &instrType[0]);
    scanf("%d", &time[0]);
    printf("\nContinue? (Y/N) ");
    scanf("%s", &continued);
    i = i + 1;

    while (continued == 'Y' || continued == 'y')
    {
        printf("\nL-lock a resource");
        printf("\nU-unlock a resource");
        printf("\nC-compute");
        printf("\nPlease Enter The Instruction Type ");
        printf("Time Input:");
        scanf("%c", &instrType[i]);
        scanf("%d", &time[i]);
        printf("\nContinue? (Y/N) ");
        scanf("%s", &continued);
        i = i + 1;
    }

    return 0;
}

The expected value should be: L1 L2 C3 U1 My Screenshotenter image description here

The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(

1

2 Answers 2

1

You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"

Sign up to request clarification or add additional context in comments.

Comments

0

The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input. To avoid this problem put a space before %c ==> scanf(" %c", &char)

#include <stdio.h>

int main()
{
    char continued;
    int i = 0;
    char instrType[10];
    int time[10];

    do
    {
        printf("L-lock a resource\n");
        printf("U-unlock a resource\n");
        printf("C-compute\n");
        printf("Please Enter The Instruction Type and Time Input: ");
        scanf(" %c%d", &instrType[i], &time[i]);
        printf("Continue? (Y/N) ");
        scanf(" %c", &continued);
        i++;
    } while (continued == 'Y' || continued == 'y');

    return 0;
}

Other things:

Instead of i = i + 1 you can use i++

Instead of using a while() is better using a do{...}while() for saving some line of code.

You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.