Home > Blockchain >  Taking multiple scans in C
Taking multiple scans in C

Time:08-15

this may be a silly question but is there a way for me to scan in multiple inputs for example I scan one key which then runs through traverse_search, after that, it takes another scan to perform the same task. At the moment it is only able to take 1 scan, performing the task only once.

*Note MAXLEN = 128

void list_search(list_t* list, FILE* outFile){
    char key[MAXLEN   1];
    while(scanf("9[^\n]", key)){
        traverse_search(list, key, outFile);
    }
}

CodePudding user response:

The issue you are facing has to do how scanf read the input buffer.

With your current format string, scanf reads at most 129 characters (or when it encounters a newline \n) into the key array.

This means that the next character in the input buffer is \n. On the second call to scanf, the first character in the input buffer is a newline and the scanning will fail and scanf return 0 (and the loop exits).

If we assume that the user will only type one newline at the end of the input, you could add a call to getc in your code and discard the read value.

void list_search(list_t* list, FILE* outFile){
    char key[MAXLEN   1];
    getc(stdin); // read the newline and hope the next character is not a newline again
    while(scanf("9[^\n]", key)){
        traverse_search(list, key, outFile);
    }
}

Please not that your code does not handle EOF. When hit with an EOF on the standard input, your code will loop forever (in case of EOF, scanf return EOF, usually -1).

I would strongly advise to use a more robust way of scanning and validating the input, such as with getline and sscanf.

CodePudding user response:

Code never consumes '\n'

scanf("9[^\n]", key) returns 0 on the next call as it fails to scan '\n' left over from the first line of user input.

Lead with a " " in the format to consume all optional leading white-space including the prior line's '\n'.

Even better, look to fgets() to read a line of user input and avoid scanf() until you understand why it is bad.

Off-by-one

To read a max length of 128, use "8[^\n]".

Test for success

while(scanf("9[^\n]", key)) loops when scanf() returns 1 or EOF. Instead, loop on success.

// while(scanf("9[^\n]", key))
while(scanf("9[^\n]", key) == 1)

void list_search(list_t* list, FILE* outFile){
  char key[MAXLEN   1];
  //           v--- consume optional leading white-space including prior \n
  while(scanf(" 8[^\n]", key) == 1) {
    traverse_search(list, key, outFile);
  }
}

CodePudding user response:

I made the key into an array of length 10, the following code will take 10 simultaneous inputs and then perform traverse search on them.

void list_search(list_t* list, FILE* outFile){
    char key[10][MAXLEN   1];
    for (int i = 0; i<10; i  ){
       scanf("9[^\n]", key[i]);
    } 
    
    for (int i =0; i<10; i  ){
        traverse_search(list, key[i], outFile); 
    }
}
  •  Tags:  
  • c
  • Related