-2

What is wrong with this code? I'm trying to compare string and white space.

void main()
{
    char d;
    int i;
    char* mystring="Vikram Natarajan";
    char c=mystring[0];
    printf("%c\n",c);
    for(i=0;i<100; i++)
    {
        if(mystring[i]==" ")
        {
            d=mystring[i+1];
        }
    }
    printf("%c\n",d);
}
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
vikramnr
  • 93
  • 2
  • 12
  • 3
    Well you don't say what it must do so how can we know what is wrong? – Stargateur Jan 18 '17 at 05:44
  • 3
    There's a lot of things wrong; which one exactly are you asking about? For instance, what is `d` supposed to be? Your string isn't 100 characters long, etc. – Ken Y-N Jan 18 '17 at 05:44
  • 1
    In general, the answer to [What should `main()` return?](http://stackoverflow.com/questions/204476/) is "an `int`" and not `void`. Microsoft gives you an excuse to use `void`, but portable code avoids that. – Jonathan Leffler Jan 18 '17 at 05:44
  • 1
    What you want to achieve and what this code is not doing? – Daksh Gupta Jan 18 '17 at 05:45
  • 2
    Maybe you're missing a `break;` after the assignment to `d`, but your loop condition is reprehensible (you read out of bounds of the array) and and you don't ensure that `d` is set even if there is no space in the string. – Jonathan Leffler Jan 18 '17 at 05:46
  • Thanks all for above comments. I didn't post this one properly. My apologies for that. – vikramnr Jan 18 '17 at 06:08

2 Answers2

1

Replace

if(mystring[i]==" ")

With

if(mystring[i]==' ')

Use a single quote for char comparison.

VHS
  • 9,534
  • 3
  • 19
  • 43
1

Adding to the correct answer, you could also use isspace from ctype.h. This function basically checks if the passed character mystring[i] is a whitespace or not. So instead of:

if(mystring[i]==' ')

you could do:

if (isspace(mystring[i]))
RoadRunner
  • 25,803
  • 6
  • 42
  • 75