user3027779
user3027779

Reputation: 73

Trouble using a loop to add characters to an array of "strings" in c?

So i tried this both with the datatype char and then the data type int. Nomatter what the printf shows only the first letter of the inputted word. For example if someone inputs dog it will just say 'd'. My guess is maybe the syntax of word[i] only takes the first letter but im not sure how to fix that. Does anyone know how to fix this?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    #define pause system("pause")
    #define cls system("cls")


void getUserWords(int *counter, int words[]){
            int i;

            printf("How many words would you like to enter into the cross word puzzle\n");
            scanf("%i",&*counter);
            for(i=0; i < *counter; i++){
                printf("Please enter word #%i\n",i+1);
                scanf("%s",&words[i]);
                printf("The word %c will be added to the crossword puzzle\n",words[i]);
                pause;
                cls;
            }//end for

            printf("Your all your words have been successfully added to the crossword puzzle");
            cls;
        }//end getUserWords

Upvotes: 0

Views: 1592

Answers (2)

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

int words[] words is an array of integers which can hold only ints of specified size. Now when you use, scanf("%s",&words[i]); you're are trying to read a string into just a each integer location which is in-correct. Thats the reasons you are able to store only first character even though you enter a string.

Upvotes: 1

James McPherson
James McPherson

Reputation: 2576

If you read your C library documentation relating to printf() and friends, you would remember that "%c" is the format string for single characters. If you want to print a string up to a terminating NULL, you should use "%s".

You have:

 printf("The word %c will be added to the crossword puzzle\n",words[i]);

But you should have

 printf("The word %s will be added to the crossword puzzle\n",words[i]);

Also, make sure that your second arg to the function has enough space allocated to store counter words.

Upvotes: 2

Related Questions