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

时间:2013-10-13 14:59:07

标签: c string

我目前正在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;

}

任何方法都将受到赞赏。

2 个答案:

答案 0 :(得分:1)

  

在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 
    }  

答案 1 :(得分:0)

阅读输入后,可能会将每个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);