简体   繁体   中英

fgets inside a loop C

  char in[20];
  char out[20];
  for(int i=0; i < nEdges ;i++){

     char str[50];
     fgets(str, 50, stdin);
     char *result = NULL;
     result = strtok(str, " ");
     int count = 0;
     int i = 0;
     char name[2][20];

     while(result != NULL){
       strncpy(name[i],result,20);
       result = strtok( NULL, " ");
       count++;
       i++;
    }

    if(count > 2){
      errorMsg2();
    }else{
      i = strlen(name[1]);
    for(int x=0; x < i ;x++){
      if(name[1][x] == '\n')
        name[1][x] = '\0';
      strncpy(out,name[0],20);
      strncpy(in,name[1],20);
    }

Hi, I am trying to read a line and verify rather there is only two element, else error message. This is all inside a for loop, when i execute the program, fgets never asked me for input. does fgets work inside a loop?

It does not matter if fgets is used inside a loop or not. There is likely a different issue. Using a debugger to step through it would be the best bet.

One potential issue is the loop that does the strncpy into name . If there are more than two items in the buffer, then it will write outside the bounds of the name array. It would probably be good to add a check to avoid that possibility prior to the overwrite (rather than after).

Another possible issue is the use of variable i . You may have some scoping issues. That variable is used in the main loop and then is updated inside that loop via a call to strlen . That would likely cause the main loop to end early (depending on the value of nEdges and the length of name[1] . In either case, it is probably not the desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM