tags:

views:

644

answers:

4

I'm having a hard time coding understanding the format of the specifier and string functions.

My aim is to use %[] to readin all characters and spaces and then use the strcpy function followed by the strcat function.

So far i've managed to enter individual characters and print them out, excluding spaces.

here's the code so far;

int main(int argc, char** argv)  {
    char words[30];
    int loops;
    printf("How many letters would you like to enter? - ");
    scanf("%d",&loops);
    for(int i=0;i<loops;i++){
      printf("Provide some text as input:");
      scanf("%s", &words[i]);
    }
    printf("%d", strlen(words));

    printf("%s",&words);
    return (EXIT_SUCCESS);
}
A: 

See this one.

Ilya
A: 

words[i] is a single character in the string words and you are trying to store a string 's' in it.
To read a single character use %c.

Martin Beckett
A: 

If you want to get a character you would use:

scanf("%c", &words[i]);

You also need to terminate the string when you are done:

words[loops]='\0';

When you print your final string you need to pass the pointer (not the address to the pointer):

printf("%s",words);

Your code will also need to handle a user that cancels or want to enter more than 29 characters.

Peter Olsson
+4  A: 

I assume you want to read a string with a maximum length of 29 characters from the standard input up to the ENTER key.

To do that you can use the following code:

char phrase[30];
printf("Enter a phrase: ");
scanf("%29[^\n]", phrase);
printf("You just entered: '%s'\n", phrase);

The %29[^\n] says to read at most 29 characters (saving one for the zero terminator) from the beginning up to the ENTER key. This includes any space characters that may be entered by the user.

smink
I know this is old, but you should fix your example code. The question was tagged C, not C++, so `cout << ...` is bogus.
R..
done, changed cout to printf.
smink