我有一个函数,它接受一个char数组并在表中搜索该特定字符及其相应的值。我正在使用 fgets 从用户输入中获取要搜索的字符,当我将缓冲区传递给 lookUp 函数时,它包含空终止字符,这会导致问题,因为查找正在寻找字符 + 空终止符。我的问题是,有没有办法"剥离"字符数组的空终止符,或者是否有不同的方法来解决这个问题?谢谢。
//lookUp function
//This function was provided for us, we cannot change the arguments passed in.
Symbol* lookUp(char variable[]){
for (int i=0; i < MAX; i++){
if (strcmp(symbols[i].varName, variable)==0){
Symbol* ptr = &symbols[i];
return ptr;
}
}
return NULL;
}
//main
int main(){
char buffer[20];
Symbol *symbol;
printf("Enter variable to lookupn");
while (fgets(buffer, sizeof(buffer), stdin)!= NULL){
printf("buffer is : %sn", buffer);
int i = strlen(buffer);
printf("length of buffer is %dn", i);
symbol = lookUp(buffer);
printf("Passed the lookupn");
if (symbol == NULL){
printf("Symbol is nulln");
}
}
}
输出,符号在这里不应为空。
Enter variable to lookup
a
buffer is : a
length of buffer is: 2 //this should only be 1
Passed the lookup
Symbol is null
不,这与终止NUL
字符无关。如果你读过strlen()
手册,你就会知道它在计算长度时不包括终止的零字节。它是fgets()
追加到字符串末尾的换行符。您可以通过将其替换为 NUL 字节来剥离它:
char *p = strchr(buffer, 'n');
if (p != NULL) {
*p = 0;
}
fgets() 保留换行符(如果有的话)。您要删除它。一种方法是:
while (fgets(buffer, sizeof(buffer), stdin)!= NULL){
char *p = strchr(buffer, 'n'); // new code
if(p) *p = 0; // new code
printf("buffer is : '%s'n", buffer);
int i = strlen(buffer);
printf("length of buffer is %dn", i);