我正在创建一个函数findBookID
。当我尝试将book id转换为整数时,它会向我显示错误
任何人都可以为我提供解决方案吗?问候。
该错误在帖子中排在最后。
strncpy(bookId, source + pos_text + 1, len_text - pos_text);
int i = atoi(bookId); //atoi converts the string to integer
if (id == i)
{
return true;
}
以下是我如何声明函数
bool findBookId(char source[], int id)
{
char input[10] = "Book ID: ";
char bookId[5];
int int_id = 0;
int pos_search = 0;
int pos_text = 0;
int len_search = 10;
size_t len_text = strlen(source);
if (len_search < len_text)
{
for (pos_text = 0; pos_text < len_search - 1; ++pos_text)
{
if (source[pos_text] == input[pos_search])
{
++pos_search;
if (pos_search == len_search - 1)
{
// match
strncpy(bookId, source + pos_text + 1, len_text - pos_text);
int i = atoi(bookId); //atoi converts the string to integer
if (id == i){
return true;
}
}
}
else
{
pos_text -= pos_search;
pos_search = 0;
}
}
}
return false;
}
参考文献的完整编码:https://drive.google.com/open?id=1zHc_26kFPVHs0b99-gkX1hdQ3AYykCPL9KegI5QobdY
答案 0 :(得分:2)
许多IDE的主要问题是缺乏清晰的警告。如果我尝试使用GCC编译代码(Google不适合代码,您的条目遭受C&amp; P错误),我会收到以下错误:
$ gcc -g3 -std=c11 -W -Wall bookid.c -o bookid
bookid.c: In function ‘addbook’:
bookid.c:106:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[50]’ [-Wformat=]
scanf("%s", &book.name);
^
bookid.c: In function ‘editbook’:
bookid.c:180:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[50]’ [-Wformat=]
scanf("%s", &book.name);
^
bookid.c: In function ‘deletebook’:
bookid.c:270:5: warning: format ‘%c’ expects a matching ‘int’ argument [-Wformat=]
printf("%c, c");
^
bookid.c: In function ‘findBookId’:
bookid.c:469:18: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
if (len_search < len_text) {
^
bookid.c:464:7: warning: unused variable ‘int_id’ [-Wunused-variable]
int int_id = 0;
^
/tmp/ccijPXxB.o: In function `main':
bookid.c:85: undefined reference to `search'
collect2: error: ld returned 1 exit status
对于第一个错误,将scanf("%s", &book.name);
更改为scanf("%s", book.name);
错字printf("%c, c");
应为printf("%c", c);
comparison between signed and unsigned integer
现在可以忽略(但是当然应该稍后修复!)
如果您不需要变量,请将其注释掉。
最后一个,致命错误,其原因是名为Search()
的函数名为search()
。 C区分大小写。
区分大小写在搜索损坏方面也扮演着重要角色:您保护文件booklist.txt
但是想要从BookList.txt
读取(这在Windows中仍然有效吗?)。