1

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);
}
MPelletier
  • 16,256
  • 15
  • 86
  • 137
  • Please clarify your question. There is no %[] in the code you provide, and your explanation explains more _how_ you intend to code somethiong rather than _what_ you need to code. If you explain your objectives better, we should be able to figure out if %[] is the right solution and how to use it. –  Oct 20 '08 at 14:35
  • See that other question: [parsing input with scanf in C](http://stackoverflow.com/questions/217074/parsing-input-with-scanf-in-c). – Ilya Oct 20 '08 at 13:44

3 Answers3

6

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.

Jorge Ferreira
  • 96,051
  • 25
  • 122
  • 132
0

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
  • 94,801
  • 28
  • 188
  • 263
0

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
  • 1,302
  • 3
  • 13
  • 19