0

The program generates a blank space at the first line of the "data.txt" file and also generates a one more serial number.

    #include<stdio.h>
    #include<string.h>
    
    int main(){
        int limit;
        int i = 0;
        printf("How many approxmiate size of your list will be: \n");
        scanf("%d", &limit);
        char list[100][100];
         
        
        FILE *store;
        store = fopen("data.txt", "w");
        while(i<=(limit - 1)){
            printf("Enter task: \n");
            gets(list[i]);
            fprintf(store,"%s\n%d)",list[i], i+1); 
            i++;
        }
    
        fclose(store);
        return 0;
    }
darshdas64
  • 19
  • 2
  • 2
    As a side note: `gets()` is dangerous and shouldn't be used, read the reason [here](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – JASLP doesn't support the IES Aug 13 '21 at 12:33
  • @JustASimpleLonelyProgrammer , thank you for the tip but the problem is in the while loop where is prints one empty character in the first line and also prints an extra serial number at the end – darshdas64 Aug 13 '21 at 12:36
  • 1
    It's not very clear what you're saying the problem is. A (very short) example of the input given to the program and the resulting file contents would help. – Thomas Jager Aug 13 '21 at 12:39
  • I remain baffled by the practice of reading parameters from stdin. `int main(int argc, char **argv) { int limit = argc > 1 ? strtol(argv[1], NULL, 10) : 1; ...` – William Pursell Aug 13 '21 at 12:51
  • 1
    And `while(i<=(limit - 1))` is much easier to read and understand as `while(i < limit)` or even better as `for ( int = 0; i < limit; i++ )`. – Andrew Henle Aug 13 '21 at 14:24
  • gets remained an official part of the language up to the 1999 ISO C standard, but it was officially deprecated by the 2011 standard and removed in the 2014 standard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it. – user3629249 Aug 15 '21 at 13:00

1 Answers1

2

It's because the linefeed ('\n') after scanf("%d", &limit); remains in the input buffer, either change scanf("%d", &limit); to scanf("%d ", &limit); or better yet, don't use gets() at all (it's dangerous to use gets(): read the reason here), instead use fgets() or scanf().

So your final code may look like this:

#include<stdio.h>
#include<string.h>

int main(){
    int limit;
    int i = 0;
    printf("How many approxmiate size of your list will be: \n");
    scanf("%d", &limit);
    char list[100][100];
     
    
    FILE *store;
    store = fopen("data.txt", "w");
    while(i<=(limit - 1)){
        printf("Enter task: \n");
        scanf(" %99[^\n]",list[i]);
        fprintf(store,"%s\n%d)",list[i], i+1); 
        i++;
    }

    fclose(store);
    return 0;
}