1

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

}

任何方法将不胜感激。

4

2 回答 2

1

检测标准输入上的空字符串和C中的tolow函数

 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 转换为其等效的小写字母。如果不可能进行这样的转换,则返回的值是 ch 不变。

   for(i = 0; search_for[i]; i++){
      search_for[i] = tolower(search_for[i]); // convert your search_for to lowercase 
    }  
于 2013-10-13T15:10:03.623 回答
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);
于 2013-10-13T17:40:58.903 回答