代码之家  ›  专栏  ›  技术社区  ›  Peeyush

如何读取用户在C中输入的字符串?

  •  46
  • Peeyush  · 技术社区  · 15 年前

    我想用C程序读取我的用户输入的名称。

    为此,我写道:

    char name[20];
    
    printf("Enter name: ");
    gets(name);
    

    但是使用 gets 不是很好,那么有什么更好的方法呢?

    6 回复  |  直到 7 年前
        1
  •  79
  •   paxdiablo    15 年前

    gets scanf fgets stdin

    #include <stdio.h>
    #include <string.h>
    
    #define OK       0
    #define NO_INPUT 1
    #define TOO_LONG 2
    static int getLine (char *prmpt, char *buff, size_t sz) {
        int ch, extra;
    
        // Get line with buffer overrun protection.
        if (prmpt != NULL) {
            printf ("%s", prmpt);
            fflush (stdout);
        }
        if (fgets (buff, sz, stdin) == NULL)
            return NO_INPUT;
    
        // If it was too long, there'll be no newline. In that case, we flush
        // to end of line so that excess doesn't affect the next call.
        if (buff[strlen(buff)-1] != '\n') {
            extra = 0;
            while (((ch = getchar()) != '\n') && (ch != EOF))
                extra = 1;
            return (extra == 1) ? TOO_LONG : OK;
        }
    
        // Otherwise remove newline and give string back to caller.
        buff[strlen(buff)-1] = '\0';
        return OK;
    }
    

    // Test program for getLine().
    
    int main (void) {
        int rc;
        char buff[10];
    
        rc = getLine ("Enter string> ", buff, sizeof(buff));
        if (rc == NO_INPUT) {
            // Extra NL since my system doesn't output that on EOF.
            printf ("\nNo input\n");
            return 1;
        }
    
        if (rc == TOO_LONG) {
            printf ("Input too long [%s]\n", buff);
            return 1;
        }
    
        printf ("OK [%s]\n", buff);
    
        return 0;
    }
    
        2
  •  17
  •   Adi Lester    13 年前

    getline()

    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
    {
        char *buffer = NULL;
        int read;
        unsigned int len;
        read = getline(&buffer, &len, stdin);
        if (-1 != read)
            puts(buffer);
        else
            printf("No line read...\n");
    
        printf("Size read: %d\n Len: %d\n", read, len);
        free(buffer);
        return 0;
    }
    
        4
  •  2
  •   nicanz    10 年前

    char*string_acquire(char*s,int size,FILE*stream){
        int i;
        fgets(s,size,stream);
        i=strlen(s)-1;
        if(s[i]!='\n') while(getchar()!='\n');
        if(s[i]=='\n') s[i]='\0';
        return s;
    }
    

        5
  •  1
  •   wonder.mice    10 年前

    fgetln

    #include <stdio.h>
    
    char *
    fgetln(FILE *stream, size_t *len);
    

    size_t line_len;
    const char *line = fgetln(stdin, &line_len);
    

    line \n

        6
  •  0
  •   user1938455    12 年前

    scanf("%[^\n]",name);