0

For part of a homework assignment I need to loop a prompt that has the user enters words until they either enter 20 words or until they enter the word 'done'. Currently, I have both parameters satisfied, but when if I enter the word 'done', it gets scanned into the array as well, which is not what I want to do.

This is my current function:

int row = 0;
int column = 0;
int i = 0;

while(i < 20)
    {
      printf("Enter words you would like hidden in the puzzle. Type 'done' when finished:\n");
      scanf("%s",a[i]);

      if(strcmp(a[i],"done") == 0)
      {
        break;
      }

      if((strlen(a[i]) > row) || (strlen(a[i]) > col))
      {
        printf("Error. Word was too long to enter into puzzle.\n");
      }

      else
      {
        i++;
      }
    }

The array 'a' is an array of character strings. I know that the line scanf("%s",a[i]); is scanning the word 'done' into the array, I just don't know how to tweak it so that doesn't happen. Can someone please help me figure this part out?

9
  • What do you think the scanf("%s",a[i]); line is doing? Commented Mar 31, 2014 at 2:00
  • 2
    What is "a". An array of ? Commented Mar 31, 2014 at 2:00
  • 1
    You could do a i--; in your "done" if. Or you could do a[i] = NULL depending on the type of a and what you're doing after this while. Commented Mar 31, 2014 at 2:01
  • Or you could read the name into a spare string (char data[32]; or whatever) and if it is not done, copy it into the target array — a in your code. But simply decrementing the count is simpler. Commented Mar 31, 2014 at 2:07
  • @Bidu - if a[i] is an array, that won't work. If it's a pointer then it should be pointing to dynamically allocated memory, so that would be a memory leak. Commented Mar 31, 2014 at 2:19

1 Answer 1

1

Try this:

char input[256];
while(i < 20)
{
  printf("Enter words you would like hidden in the puzzle. Type 'done' when finished:\n");
  scanf("%s",&input);
  if(strcmp(input,"done") != 0)
  {
    strcpy(a[i],input);
    if((strlen(a[i]) > row) || (strlen(a[i]) > col))
    {
      printf("Error. Word was too long to enter into puzzle.\n");
    }
    i++;
  }
  else
    break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@MattMcNabb: Used to be a c# programmer. :-) Anyway, edited my answer. Thanks.
I think you might need an strcpy instead of a[i] = input. Also, I think scanf("%s",input); not scanf("%s",&input);.

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.