How to correctly input a string in C

前端 未结 5 1982
忘掉有多难
忘掉有多难 2021-01-22 14:38

I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fin

5条回答
  •  心在旅途
    2021-01-22 15:21

    Please, FORGET that scanf exists. The problem you are running into, whilst caused mostly by your understandable inexperience, will continue to BITE you even when you have experience - until you stop.

    Here is why:

    scanf will read the input, and put the result in the char buffer you provided. However, it will make no check to make sure there is enough space. If it needs more space than you provided, it will overwrite other memory locations - often with disastrous consequences.

    A safer method uses fgets - this is a function that does broadly the same thing as scanf, but it will only read in as many characters as you created space for (or: as you say you created space for).

    Other observation: sizeof can only evaluate the size known at compile time : the number of bytes taken by a primitive type (int, double, etc) or size of a fixed array (like int i[100];). It cannot be used to determine the size during the program (if the "size" is a thing that changes).

    Your program would look like this:

    #include 
    #include 
    
    #define BUFLEN 100          // your buffer length
    
    int main(void)    // <<< for correctness, include 'void'
    {
        int siz;
        char i[BUFLEN];    // <<< now you have space for a 99 character string plus the '\0'
    
        printf("Enter a string.\n");
        fgets(i, BUFLEN, stdin);   // read the input, copy the first BUFLEN characters to i
    
        siz = sizeof(i)/sizeof(char);  // it turns out that this will give you the answer BUFLEN
                                       // probably not what you wanted. 'sizeof' gives size of array in
                                       // this case, not size of string
                                       // also not
    
        siz = strlen(i) - 1;           // strlen is a function that is declared in string.h
                                       // it produces the string length
                                       // subtract 1 if you don't want to count \n
        printf("The string length is %d\n", siz);  // don't just print the number, say what it is
                                                   // and end with a newline: \n
        printf("hit  to exit program\n");    // tell user what to do next!
        getc(stdin);
        return 0;
    }
    

    I hope this helps.

    update you asked the reasonable follow-up question: "how do I know the string was too long".

    See this code snippet for inspiration:

    #include 
    #include 
    
    #define N 50
    
    int main(void) {
      char a[N];
      char *b;
    
      printf("enter a string:\n");
    
      b = fgets(a, N, stdin);
    
      if(b == NULL) {
        printf("an error occurred reading input!\n"); // can't think how this would happen...
        return 0;
      }
    
      if (strlen(a) == N-1 && a[N-2] != '\n') {       // used all space, didn't get to end of line
        printf("string is too long!\n");
      }
      else {
        printf("The string is %s which is %d characters long\n", a, strlen(a)-1); // all went according to plan
      }
    
    }
    

    Remember that when you have space for N characters, the last character (at location N-1) must be a '\0' and since fgets includes the '\n' the largest string you can input is really N-2 characters long.

提交回复
热议问题