![](/img/trans.png)
[英]c programming - Why this simple calculator using switch doesn't work
[英]C-Programming.Why Doesn't This Work?
以下程序应搜索多维数组。 当我输入town
一词作为输入时,它应该返回Track 1: Newark,Newark-A Wonderful Town
但我没有收到任何输出(什么也没有发生),有什么解决办法?
我正在编写《 Head First C》书。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Run this program using the console pauser
or add your own _getch, system("pause") or input loop */
char tracks[][80]={
"I Left My Heart In Harvard Med School",
"Newark,Newark-A Wonderful Town",
"From Here to Maternity",
"The Girl From Iwo Jima",
};
void find_track(char search_for[]){
int i;
for (i=0;i<=4;i++){
if(strstr(tracks[i],search_for)){
printf("Track %i:'%s' \n",i,tracks[i]);
}
}
}
int main(int argc, char *argv[]) {
char search_for[80];
printf("Search for: ");
fgets(search_for,80,stdin);
find_track(search_for);
return 0;
}
如上所述, fgets
从您的输入中存储换行符,它将不匹配。 只要您在标题中匹配测试的大小写,从该search_for
字符串中search_for
最后一个字符就可以使它工作。 另外,请注意,您的for
循环应使i < 4
而不是i <= 4
。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char tracks[][80]={
"I Left My Heart In Harvard Med School",
"Newark,Newark-A Wonderful Town",
"From Here to Maternity",
"The Girl From Iwo Jima",
};
void find_track(char search_for[]){
int i;
for (i=0;i<4;i++){
if(strstr(tracks[i], search_for)){
printf("Track %i:'%s' \n",i,tracks[i]);
}
}
}
int main(int argc, char *argv[]) {
char search_for[80];
printf("Search for: ");
fgets(search_for,80,stdin);
search_for[strlen(search_for)-1] = '\0'; // truncate input
find_track(search_for);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.