I am creating a function findBookID
. When I try to convert the book id into integer it shows me an error.
can anyone provide me a solution to solve this? Regards.
The error is last in the post.
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;
}
Here is how i declare the function
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;
}
Full coding for Reference:https://drive.google.com/open?id=1zHc_26kFPVHs0b99-gkX1hdQ3AYykCPL9KegI5QobdY
This is the error message: function call is not allow a constant expression
A main problem of many IDEs is the lack of legible warnings. If I try to compile your code (Google is not good for code, your entry suffers from C&P errors) with GCC I get the following errors:
$ 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
For the first errors change scanf("%s", &book.name);
to scanf("%s", book.name);
The typo printf("%c, c");
should be printf("%c", c);
comparison between signed and unsigned integer
can be ignored for now (but should be repaired later, of course!)
If you do not need a variable, comment it out.
The last one, the fatal error, has its cause with a function named Search()
called by the name of search()
. C is case-sensitive.
Case sensitivity also plays a large role with the broken search: you safe the file booklist.txt
but want to read from BookList.txt
(does that still work in Windows?).