-3

I have searched and can't work out why why I am getting this error if it is declared within the for loop?

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main (void)
{
    char* sur;
    char* space = " ";
    char* name = GetString();

    printf("%c\n", name[0]);

    for(int i = 0, n = strlen(name); n < i; i++);
    {
        if (strcmp(name[i],space)==0)
        {
        sur = name[i + 1];
        }
        else
        {
        return 0;
        }
    }
    printf("%s\n", sur);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ryan McCauley
  • 17
  • 1
  • 2
  • 1
    what error? on what variable? is this the working version or the failing one? – Andrew Jaffe May 31 '16 at 11:31
  • 1
    for variable `n`, i guess? – Sourav Ghosh May 31 '16 at 11:31
  • When asking about error message, **always** include the **complete** error message in your question. Please [edit] your post and add it there. – user694733 May 31 '16 at 11:33
  • 1
    `for(int i = 0, n = strlen(name); n < i; i++);` remove last `;`. Also `n < i;` --> `i < n;` and `if (strcmp(name[i],space)==0)` --> `if (name[i] == ' ')` – BLUEPIXY May 31 '16 at 11:34
  • 1
    ...because the loop already terminated, `i` has gone out of scope. – Weather Vane May 31 '16 at 11:35
  • Where is n declared? – exilit May 31 '16 at 11:38
  • _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting._ – Sourav Ghosh May 31 '16 at 11:40

3 Answers3

4

You have an extra semicolon after your loop declaration:

for(int i = 0, n = strlen(name); n < i; i++);

this will cause your variables i and n to be undeclared in your expected loop body

Henningsson
  • 1,275
  • 1
  • 16
  • 23
2

The reason is ; at the end:

//...
for(int i = 0, n = strlen(name); n < i; i++)
//...
Igor B.
  • 2,219
  • 13
  • 17
2
  for(int i = 0, n = strlen(name); n < i; i++);

You CANNOT place a semi-colon at the end of the for-loop declaration. The ; is a valid statement, and because C/C++ allows you omit curly braces {} when using single-statements for the bodies of loops (and if statements), this means you have a for-loop over an empty body! Do this instead:

 for(int i = 0, n = strlen(name); n < i; i++)

Another tip: define your variables outside of your for-loop and just initialize the counter in the for statement.

int n = strlen(name);
int i;
for(i = 0; n < i; i++)
gariepy
  • 3,576
  • 6
  • 21
  • 34
Alikbar
  • 685
  • 6
  • 20