0
votes

I'm only allowed to use the stdio.h library. So I want to read the user input with getchar until the first "/" and then want to save the read input in an integer array. Checking the input out of the while-loop, i recognized that only the last string is safed.

For example I type in "test/hello", I want to safe "test" in the integer array called "safe" so that I can work with it out of the while-loop too.

I have checked the input out of the while-loop with "putchar(safe[count]);" but the only safed input is the letter "t". (Based on the example above)

    #include <stdio.h>

    int count;
    char i;
    int safe[50];

    int main() {
        while (1) {
            i = getchar();
            count = 0;
            if (i == '/')
                break;
            safe[count] = i;
        }
        // putchar(safe[count]);
     }
1
You do not increase count - Neijwiert
You should also add in a check to never get to count >= 50. Also why do you store the chars as ints? - Neijwiert
Why set count to zero inside the loop? It will now just set safe[0] to i. You must increment it: safe[count++]= i; - Paul Ogilvie
In addition to breaking out if count reaches 50, you should also break out when i equals EOF. Also, safe[] can use type char instead of int to save space. - Ian Abbott

1 Answers

0
votes

See the comments as to the why, but the following is correct:

int main() {
    count= 0;
    while (count<49) {
        i = getchar();
        if (i == '/')
            break;
        safe[count++] = i;
    }
    safe[count]= '\0';
 }