# Thread: Something weird about Strings

1. ## Something weird about Strings

I have just started a code that will hopefully end up being able to differentiate any inputted function.
It is relatively simple function, so at the moment it can only do powers. so
Code:
`x^3+x^2`
would go to:
Code:
```x^3+x^2 //this is just for bug finding at the moment, and for demonstration purposes.
3x^2+2x^1 //this is the answer```
At least, that's the idea. What I actually get is:
Code:
```x^3+x^2
- ( ...then some random characters which look like something out of wingdings.```
I know that what is happening is that it is both doing some crazy stuff to the function and failing to differentiate it. What I can't figure out is why.
Here is the code:

Code:
```#include <stdio.h>
#include <stdlib.h>
int simple(char x);
int main()
{
char f[50];
int i;
char p;
int n;
printf("Write the function you want to be Differentiated: ");
fgets(f, 50, stdin);
printf("\n");
for(i=0;i<50;i++)
{
printf("%c", f[i]); //This is just in to make sure the string is right, and this is where the problems are.
}
getchar();
for(i=0;i<50;i++)
{
if (f[i]=="x" && f[i+1]=="^")
{
simple(f[i+2]);
}
if (f[i]=="+")
{
printf("+");
}
if (f[i]=="-")
{
printf("-");
}
}
getchar();
return 0;
}
int simple(char x)
{
int n;
n = atoi(&x);
printf("n");
printf("%d", n);
printf("x^");
printf("%d", n-1);
return 0;
}```

2. You're just blindly running past any legitimate characters in the array. You should determine the inputted length and the loop should terminate there.

3. Ok, that got rid of the random characters. But it's still not running the actual differentiation process.

4. Originally Posted by mortalc
Code:
```        if (f[i]=="x" && f[i+1]=="^")
{
simple(f[i+2]);
}
if (f[i]=="+")
{
printf("+");
}
if (f[i]=="-")
{
printf("-");
}```
f is an array of chars, so f[i] refers to a single char, which should be enclosed in single quotes. See all those double quotes? They make strings, which act like char pointers. That is fine for printf, but not for comparing to f[i]. Change all the double quotes to single quotes in your comparisons. Turn the warnings up on your compiler, so you can see the warnings/errors that were produced by your incorrect usage of ". Then, make sure you correct all the problems the compiler tells you about.

5. Thanks! It works perfectly now!

I have another question. Different problem, same code. Should I ask it here or on a new thread? anyway, it is how to check if a char variable is a number. So for example '3' will return positive but 'n' will not.

6. Look in ctype.h for functions like isdigit()

Popular pages Recent additions