Search code examples
carraysscanfcontinue

C scanf in loop continues automaticly without input


I'm trying to get input in an array, I expect input like the following.

5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)

So we get an array deeln[2][5] in this example. I try to get it with the following code:

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

bool isinarray(int val, int *arr, int size){
    int countimp;
    for (countimp=0; countimp < size; countimp++) {
        if (arr[countimp] == val)
            return true;
    }
    return false;
}


int main(void){

    int k, d, ci, cj, ck, ta;
    //get input
    scanf("%i", &k);
    scanf("%i", &d);

    int deeln[d][k], temp[k];

    for(ci = 0; ci < d; ci++){
        printf("d= %i, ci= %i \n", d, ci);
        scanf("%s", temp);
        for(cj = 0; cj < k; cj++){
            deeln[ci][cj] = temp[cj*2]-'0';
        }
    }

    //loop while. 
}

But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.

What to do? Has it something to do with pointers or am i using scanf wrong?

UPDATE:

If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.


Solution

  • The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:

    #include <stdio.h>
    #include <string.h>
    #include <stdbool.h>
    
    bool isinarray(int val, int *arr, int size){
        int countimp = 0;
        for (countimp=0; countimp < size; countimp++) {
            if (arr[countimp] == val)
                return true;
        }
        return false;
    }
    
    
    int main(void){
    
    
        int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
    
    
        //get input
        scanf("%i", &k);
        scanf("%i", &d);
        char temp[20];
        int deeln[d][k];
    
        memset(deeln, 0 , sizeof(deeln));
        memset(temp, 0 , sizeof(temp));
    
    
    
    
        for(ci = 0; ci < d; ci++){
            fgets(temp, 20, stdin);
            for(cj = 0; cj < k; cj++){
                ta = cj*2;
                deeln[ci][cj] = temp[ta]-'0';
            }
        }
    
        //loop while. 
        return 1;
    }
    

    Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!