• + 0 comments

    For C users. I had some head banging up the wall because of differencies how scanf worked in my WSL environment and a given here environment. Here is a program that worked in my WSL window: // Declare second integer, double, and String variables. int my_integer = 0; double my_duoble = 0.0; char *my_string; char final_string; my_string = (char)malloc(100 * sizeof(char)); final_string = (char*) malloc(200 * sizeof(char)); if(my_string == NULL || final_string == NULL) { printf("Memory allocation failed."); return 1; }

    // Read and save an integer, double, and String to your variables.
    scanf("%d", &my_integer);
    scanf("%lf", &my_duoble);   
    scanf("%[^\n]s", my_string);
    
    // Print the sum of both integer variables on a new line.
    printf("%d\n", i + my_integer);
    
    // Print the sum of the double variables on a new line.
    printf("%.1lf\n", d + my_duoble);
    
    // Concatenate and print the String variables on a new line
    // The 's' variable above should be printed first.
    strcpy(final_string, s);
    strcat(final_string, my_string);
    printf("%s\n", final_string);
    free(my_string);
    free(final_string);
    

    However, in the given environment nothing would be put into my_string. The remedy was to clean out a buffer from the previous input: <...>
    // Read and save an integer, double, and String to your variables. scanf("%d", &my_integer); scanf("%lf", &my_duoble);

    int leftover = 0;
    while ((leftover = getchar()) != '\n' && leftover != EOF);
    
    scanf("%[^\n]s", my_string);
    // Print the sum of both integer variables on a new line.
    printf("%d\n", i + my_integer);
    
        Then my program worked. But adding a buffer cleaning code in my program in WLS, caused it crash.
    

    Just wondering why that may be.... <...>

    Then my program worked. But adding a buffer cleaning code in my program in WLS, caused it crash. Just wondering why that may be....