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

int main()
{
    int size = 0;
    do
    {
        printf("Put in size of the list (Range[1;2^16-1]): ");
        scanf("%d", &size);//input
        if (size <= 0)
            printf("Put in a correct length!\n");
    } while (size <= 0);
    char temp[size+1];
    while (fgets(temp, size, stdin))//break with ^Z or ^D
    {
    }
    for (int i = 0; i < size; i++)//output
    {
        printf("%c", temp[i]);
        printf("%d", i);
    }
    return 0;
}

Output:

Put in size of the list (Range[1;2^16-1]): 5
pizza
^Z(my powershell input)
a012z34

I tried to use the fgets() function but it doesnt recognize all chars, only the last two chars. So I did some research but I couldn't find anything.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • 1
    second argument to `fgets` should be `sizeof temp` (you cut it short by 1). Also the first thing `fgets` read will be the newline character left behind from inputting the size – M.M Nov 18 '22 at 07:48
  • what inputs should it recognize? – emetsipe Nov 18 '22 at 07:48
  • @M.M is referring to [this](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – emetsipe Nov 18 '22 at 07:50
  • What do you mean by "recognize"? No matter what input you get, you print exactly `size` character plus the integer value. – Gerhardh Nov 18 '22 at 07:58
  • 1
    Ah, I see, the comment generating the manual `EOF` threw me off - it's at least called once. – David C. Rankin Nov 18 '22 at 08:05

1 Answers1

1

You have a few issues:

  1. You do not consume the trailing \n from your scanf call. That leads to your first fgets reading only "\n". This is clearly not what you would want but as you run fgets in a loop it does not cause problems.

  2. You provide a size to fgets that does not match your buffer and cannot hold your input. Your buffer is 6 bytes but you only provide 5 to fgets. 5 Bytes are not enough to hold "pizza" as there is no room for \0. It also does not hold the \n for that line. This means you will first get "pizz" and immediately afterwards you will get "a\n\0". The remaining 3 bytes from the buffer will be unchanged ans still hold "z\0" from previous call.

  3. After you end with ^D you print the content. But for values \n, \0 etc. you will not see something that you typed. That is why you don't see anything between your numbers.

You could make all input visible by printing like this: printf("%d: '%c' (%d)\n", i, temp[i], temp[i]);

Solution: If you want to get input with up to 5 characters, you need a buffer of 7 bytes and you must provide that size to fgets.

user3386109
  • 34,287
  • 7
  • 49
  • 68
Gerhardh
  • 11,688
  • 4
  • 17
  • 39