How to read from input until newline is found using scanf()?

后端 未结 8 1599
野性不改
野性不改 2020-11-30 05:58

I was asked to do a work in C when I\'m supposed to read from input until there\'s a space and then until the user presses enter. If I do this:

scanf(\"%2000         


        
相关标签:
8条回答
  • 2020-11-30 06:49
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    int main(void)
    {
      int i = 0;
      char *a = (char *) malloc(sizeof(char) * 1024);
      while (1) {
        scanf("%c", &a[i]);
        if (a[i] == '\n') {
          break;
        }
        else {
          i++;
        }
      }
      a[i] = '\0';
      i = 0;
      printf("\n");
      while (a[i] != '\0') {
        printf("%c", a[i]);
        i++;
      }
      free(a);
      getch();
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-30 06:50

    I am too late, but you can try this approach as well.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int i=0, j=0, arr[100];
        char temp;
        while(scanf("%d%c", &arr[i], &temp)){
            i++;
            if(temp=='\n'){
                break;
            }
        }
        for(j=0; j<i; j++) {
            printf("%d ", arr[j]);
        }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题