c - 如何使用 strstr 但使用用户未指定的关键字搜索字符串
问题描述
这是代码
int main()
{
FILE* fptr;
char c_id[50];
char str[BUFFER_SIZE];
int choices;
char* pos;
int customer_id;
printf("Enter customer ID: ");
scanf("%d", &customer_id);
sprintf(c_id, "%d", customer_id);
fptr = fopen("servicestest.txt", "r");
printf("\n1. Check for unpaid\n2. Check for paid\n");
scanf("%d", &choices);
switch (choices)
{
case 1:
while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
{
pos = strstr(str, "Not");
if (pos == 1)
{
printf("%s\n", str);
}
}
break;
case 2:
while ((fgets(str, BUFFER_SIZE, fptr)) != 0)
{
pos = strstr(str, "Not");
if (pos =! 1)
{
printf("%s\n", str);
}
}
}
}
是否计划用 not 检查一行并打印它们如何做到这一点?为什么当我输入“1”作为选项时它不打印任何东西
我想分配
char ch[50];
ch[1] = "Not";
但是当我尝试时strstr (str, ch[1])
它导致了一个错误
知道怎么做吗?
解决方案
- 检查返回值
fopen
:
if(!fptr) {
return -1;
}
- 您尝试在指针和
int
值之间进行比较。
if (pos == 1)
// and
if (pos =! 1) // even you can compare, it should be if (pos != 1)
如果要计算 substring 的位置"Not"
,可以这样做:
pos = strstr(str, "Not");
if(pos) {
int pos_substring = (int) (str-pos);
// from here you can compare the position of substring with an `int` value.
if (pos_substring == 1) {/*do something*/}
eles {/*do something*/}
}
- 当您尝试代码时:
char ch[50];
char ch[1] = "Not"; // string "Not" need at least 4 bytes (3 bytes for 'N', 'o' and 't', 1 bytes for null character)
它应该更改为:
char ch[50] = "Not";
// or
char ch[] = "Not";
// or
const char *ch = "Not" // be attention with the string literal
然后当你想申请strstr
函数时:
strstr (str, ch); // use ch instead of ch[1]
如果你想使用类似的东西strstr (str, ch[1])
,你可以使用 2D 字符数组:
char ch[50][50] = {/*init the string here or later as you want*/}; // this 2D array contents of maximum 50 strings, each string length ups to 49.
strstr (str, ch[0]);
strstr (str, ch[1]);
strstr (str, ch[2]);
// etc.