Flushing stdin after every input - which approach is not buggy?

前端 未结 5 524
执笔经年
执笔经年 2020-12-06 07:44

After Mark Lakata pointed out that the garbage isn\'t properly defined in my question I came up with this. I\'ll keep this updated to avoid confusions.


5条回答
  •  余生分开走
    2020-12-06 08:23

    You should use getline/getchar:

    #include 
    
    int main()
    {
      int bytes_read;
      int nbytes = 100;
      char *my_string;
    
      puts ("Please enter a line of text.");
    
      /* These 2 lines are the heart of the program. */
      my_string = (char *) malloc (nbytes + 1);
      bytes_read = getline (&my_string, &nbytes, stdin);
    
      if (bytes_read == -1)
        {
          puts ("ERROR!");
        }
      else
        {
          puts ("You typed:");
          puts (my_string);
        }
    
      return 0;
    

提交回复
热议问题