#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.
You have a few issues:
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.
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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.