I defined a function, but when I call it I get an error message that says:
*undefined reference to `only_digits'
clang: error: linker command failed with exit code 1 (use -v to see invocation)*
The code is:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool only_digits(string s);
int main(int argc, string argv[])
{
if(argc > 2)
{
printf("Usage: ./caesar key\n");
}
bool only_digits(string s);
for(int i = 0, n = strlen(argv[1]); i<n; i )
if((argv[1])[i]<='z' && (argv[1])[i]>'A')
{
return false;
}
else
{
return true;
}
bool z = only_digits(argv[1]);
}
CodePudding user response:
There are several problems with your code:
You seem to try to define the function
only_digits()
within the functionmain()
. That's not how it works. You need to define (i.e. provide the body of) the function outside ofmain()
. That's the reason for the linker error you're getting.Unlike python, in C we define a block by enclosing it in
{
}
braces, not by indentation.The body of your
only_digits()
function should use thes
parameter, then you passargv[1]
(or any other string) when you call that function.The logic where you're checking for only digits is incorrect. You should return
true
only after you've checked all characters, i.e. after the loop.
Here's a reworked version:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool only_digits(string s)
{
for(int i = 0, n = strlen(s); i<n; i )
{
if(s[i]<='z' && s[i]>'A')
{
return false;
}
}
return true;
}
int main(int argc, string argv[])
{
if(argc > 2)
{
printf("Usage: ./caesar key\n");
}
bool z = only_digits(argv[1]);
}
Also, please note that your only_digits()
function doesn't really check if the string contains only digits. It only checks if there are any letters in the string. If there are any symbols like
or -
, it will still return true
.
CodePudding user response:
First of all you defined a function inside of main
, which is wrong. You should define it after or before int main(int argc, string argv[])
. Also, you should use {
}
to enclose the function.
Apart from that, only_digits(string s)
takes string s
as a parameter, but you have used argv[1]
variable inside the function. A copy is given by the name string s
which is equal to argv[1]
to the function so you should use s
(= argv[1]
) inside the function.
Also your function doesn't return a value whereas it should return a bool
.
I am not sure what this program does but the problem you are having should be solved with this new code:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool only_digits(string s);
int main(int argc, string argv[])
{
if(argc > 2)
{
printf("Usage: ./caesar key\n");
}
bool z = only_digits(argv[1]);
}
bool only_digits(string s)
{
bool x = true;
for(int i = 0, n = strlen(s); i<n; i )
{
if((s)[i]<='z' && (s)[i]>'A')
{
x = false;
}
}
return x;
}