0

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.

3
Contributors
6
Replies
8
Views
10 Years
Discussion Span
Last Post by Salem
0

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.

0

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?

0

>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.

0

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

error: invalid operands to binary +

0

>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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.