How many times will this cycle be completed?

I am writing this code that takes an integer (t) as input from a user. The cycle will be executed only "t" times. But I find that it works for (t-1)times. For example, if I give an input 3, it only starts 2once. Can someone explain why this is happening?

I tried and used scanf("%s", &str), it works, but then I can not take the line as input, containing spaces.

#include <stdio.h>
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
      {
        char str[100];
        gets(str);
        printf("%s\n", str);
      }
    return 0;
}
+4
source share
3 answers

scanf("%d", &t)consumes only the number in the input stream and leaves the rest of the characters. When you enter a number and press the enter key, a new line appears after the number.

gets , . .

+2

3 , . , 2 - , \n, gets , .
, Enter, \n . gets , \0, \n . \n ( ) gets, .


. gets. C. fgets.

+1

, scanf, , SPACE. , (t-1) , - gets(). , getch() . , ,

#include <stdio.h>
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
     {
       char str[100];
       scanf("%[^\n]c",&str);
       printf("%s\n", str);
       getch();
     }
return 0;

}

getch() , . , scanf(), ^ scanf , , ^ , escape- NEW LINE. , , . , :)

0
source

Source: https://habr.com/ru/post/1524329/


All Articles