Hello,
Is there any way of reading words from a string containg a few words separated by white spaces using a loop? I don't know how many argumets the user will input. I wanted to do it like this:

for(i=0;i<wordCounter;i++)
{
  sscanf(input,"%s",argument[i]);
}

But this keeps reading in the first word from the string.

You can use the %n conversion specifier to find out how many characters were read and adjust the source string accordingly:

#include <stdio.h>

int main( void )
{
  const char *src = "this is a test";
  char word[5];
  int n;

  while ( sscanf ( src, "%4s%n", word, &n ) == 1 ) {
    puts ( word );
    src += n;
  }

  return 0;
}

Note that the usual guideline of using the number of conversion specifiers to determine what value scanf should return doesn't apply here. %n doesn't add to the number of conversions, which is why the loop uses 1 instead of 2 to mark success.

Sorry, but I don't understand this code :( Why do you have to use puts(word) after reading in to word with sscanf? And what does += do?

>Sorry, but I don't understand this code
Gone are the days when rookies would take a new piece of code and run off to dissect it. :(

>Why do you have to use puts(word) after reading in to word with sscanf?
Because it's generally a better example if you can see that it's working. :icon_rolleyes:

>And what does += do?
It does exactly what your book on C tells you it does: adds the value on the right to the value on the left.

Yes, I did try it and all I got was a compiler error. It doesn't like src += n;

error: invalid operands to binary +

>Yes, I did try it and all I got was a compiler error.
Post the exact code you tried then, because you messed it up somehow. Also mention which compiler and OS you're using.

Sounds like bad copying on your part, replacing a pointer with an array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.