0

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]);
     }
4
  • 3
    You do not increase count Commented Apr 17, 2019 at 9:06
  • You should also add in a check to never get to count >= 50. Also why do you store the chars as ints? Commented Apr 17, 2019 at 9:07
  • Why set count to zero inside the loop? It will now just set safe[0] to i. You must increment it: safe[count++]= i; Commented Apr 17, 2019 at 9:08
  • 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. Commented Apr 17, 2019 at 9:11

1 Answer 1

0

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';
 }
Sign up to request clarification or add additional context in comments.

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.