1

I need to use j as a counter and increment it at the same time the i increments. This code just keep on giving me random number for j.

    int i, j;   // counters
    for (i=0, j=1; i<=LENGTH; i++, j++)
    {
        printf("Player %i "\n", j);
        printf("Name:\t");
        fgets(name[i], MAXLENGTH, stdin);
        ...
7
  • 2
    Additionally, this code definitely looks like it should work. Commented Sep 2, 2013 at 13:37
  • 2
    @Bathsheba: Where did you get that idea from? Commented Sep 2, 2013 at 13:45
  • 1
    @Bathsheba: huh? i = 0, j = 1 is perfectly valid. Commented Sep 2, 2013 at 13:47
  • 2
    @Bathsheba: I think you're wrong: for (i = 0, j = 1, k = 2; i < 10; i++, j++, k++) does exactly what one might expect. Commented Sep 2, 2013 at 13:48
  • 1
    @Everyone! [My previous comment (now removed) implied you can't initialise more than one variable in a for loop using comma.] Yes indeed I am incorrect but I'll leave this here otherwise nothing else here will make sense. It's declaration together with definition that you can't do with two variables in a for loop using comma. Apologies. Commented Sep 2, 2013 at 13:51

3 Answers 3

4
printf("Player %i "\n", j); 

Statement consists of two double quotes.

printf("Player %i \n", j);  

or

printf("Player %d \n", j);   

try this code:

#define LENGTH 10
#include<stdio.h>
main()
{
    int i, j;//counters
    for (i=0, j=1; i<=LENGTH; i++, j++)
    {
        printf("Player j=%i  i=%d \n", j,i);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

What about

  int i;//counter
  for (i=0; i<=LENGTH; i++)
  {
      printf("Player %i \n", i + 1);
      printf("Name:\t");
      fgets(name[i], MAXLENGTH, stdin);
  ...

4 Comments

Agreed, though you missed the double quotes before the newline in the first printf call. The real question is how did it compile with that going on? ;-)
The real question is : is is really necessary to compile a code like that? :p
I hope not, else every C compiler I have worked with gets it wrong by indicating an error. ^_^
Well, as the question was about i and j, I didn't feel the need to compile a simple printf ;)
0

You don't say what name is, but if it is simply a string, like:

char name[MAXLENGTH];

then fgets will write into the name string starting at the ith element. It is possible you are writing past the end of the name string. If name is defined locally just before your loop, then you could overwriting both i and j with "random" data (i.e. you are performing the namesake of this site).

If this is the case, then you should instead call fgets as follows:

fgets(name, MAXLENGTH, stdin);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.