繁体   English   中英

在C中的stdin和tolower函数上检测到空字符串

[英]Detect empty string on stdin and tolower function in C

我目前正在用C语言编写字典程序。如何在stdin上检测空字符串? 使用search_for作为输入。

void find_track(char search_for[])
{

        int i;
        for (i = 0; i < 5; i++) {
            if (strstr(tracks[i], search_for)){
            printf("The meaning of %s: %s\n",tracks[i], meaning[i]);

                break;
            } 
        }

        if (!strstr(tracks[i], search_for)) {
                printf("%s could not found in dictionary.\n",search_for);
            }   

}

再次,我如何使用tolower函数降低转换的输入?

int main()
{
    int setloop =1;
    titlemessage();
    do {

        char search_for[80];
        char varchar;
        printf("Search for: ");
        fgets(search_for, 80, stdin);
          if(search_for[strlen(search_for)-1]=='\n')
          search_for[strlen(search_for)-1]='\0';

        find_track(search_for);
        printf("Press ENTER to start new search\n");
        //printf("Press 'q' to exit the program\n\n");

            varchar = getchar();
            if (varchar == 10) {    
                continue;
            }else {
                break;
            }
    } while (setloop = 1);
    return 0;

}

任何方法将不胜感激。

在C中的stdin和tolower函数上检测到空字符串

 fgets(search_for, 80, stdin);
 if(search_for[strlen(search_for)-1]=='\n')
      search_for[strlen(search_for)-1]='\0';


  if(strlen(search_for)==0)
   {
   // empty string, do necessary actions here
   }

char ch;

tolower()如果ch是大写字母并且具有小写字母等效项,则将ch转换为其小写字母。 如果无法进行这种转换,则返回的值将保持不变。

   for(i = 0; search_for[i]; i++){
      search_for[i] = tolower(search_for[i]); // convert your search_for to lowercase 
    }  

读取输入后,有可能将每个char更改为小写。

  // Test fgets() return value, use sizeof
  if (fgets(search_for, sizeof search_for, stdin) == NULL) {
    break;
  }
  size_t i; 
  for (i = 0; search_for[i]; i++) {
    search_for[i] = tolower(search_for[i]);
  }
  // Advantage: we've all ready run through `search_for` & know its length is `i`.
  // Also avoid a `[strlen(search_for)-1]` which could be -1
  if ((i > 0) && (search_for[i-1] =='\n')) {
    search_for[--i] = '\0';
  }
  // If empty line entered (OP's "detect empty string on stdin")
  if (i == 0) {
    break;
  }
  find_track(search_for);

  #if 0
    // Reccomedn delete this section and using the above empty line test to quit
    //printf("Press 'q' to exit the program\n\n");
    varchar = getchar();
    if (varchar == 10) {    
      continue;
    } else {
      break;
    }
  #endif

// OP likel want to _test_ setloop (==), not _assign_ setloop (=)
// } while (setloop = 1);
} while (setloop == 1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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