0

I have to split a string-input value where-ever there is a blankspace and output the result.

eg: input:

I am a noob at C

output:

>>I 
>>am
>>a
>>noob
>>at
>>C

Code:

 void splitText(){
      char str[100];
      char sep[] = " \r\n";
      char *res; //if i remove this
      fgets(str,sizeof str,stdin);

      if (fgets(str, sizeof str, stdin) == NULL) {
          printf("error");
      }
      char *p = strchr(str, '\n');
      if (p) *p = 0;
      res = strtok(str, sep); //and this
      printf("%s\n",res); //and change this to str


 }

Working code for anyone encountering the same problem:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void splitText() {
  char str[100];
  char sep[] = " \n";
  char *res;
  fgets(str,sizeof str, stdin);
  if ( fgets(str, sizeof str, stdin) == NULL ) {
       printf("Error");
       break;
  }

  res = strtok(str, sep);
  while(res != NULL){
     printf("Splitted String: \"%s\"\n",res);
     res = strtok(NULL,sep);
  }

}

Thanks to everyone who contributed in helping me with this issue!

3
  • 1
    char str[100] = scanf("%s",str); , where did you read this? Commented Dec 8, 2015 at 16:33
  • 1
    scanf() returns an integer and you are assigning it to a char array scanf("%s",str) will do your job, just remove the left part Commented Dec 8, 2015 at 16:34
  • Whenever you have an error with a particular function go read up on it. Learning what the function returns or in this case how it stores values would have probably saved you a lot of time and trouble Commented Dec 8, 2015 at 17:03

2 Answers 2

3

The problem with

  char str[100] = scanf("%s",str);

is that you are assigning an int to a char array.

scanf() returns the number of items successfully scanned. The actual reading of chars into the array is done by scanf() itself. So you just need to call scanf() separately.

if (scanf("%s",str) != 1) { /* error */}

But scanf() is not the right tool here since you want to read a whole line. scanf() would stop at the first whitespace (after reading non-whitespace chars).

So when you type "I am a noob at C", scanf() will only read the I and ignore the rest.

What you want is to use the fgets() function to read a line:

  char str[100];

  if (fgets(str, sizeof str, stdin) == NULL) {
     /* error */
  }

/* rest of the code */

fgets() would read the newline as well if there's space in the buffer. If this is undesirable, then you can remove it:

char *p = strchr(str, '\n');
if (p) *p = 0; //remove the trailing newline.

Note: strtok() is not a thread safe function. POSIX provides strtok_r() as a thread-safe alternative. This is something to be aware of even if it doesn't matter in this specific case.


Here's a self contained example:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
  char str[100];
  char sep[] = " \n";
  char *res;

  if ( fgets(str, sizeof str, stdin) == NULL ) {
     exit(1);
  }

  res = strtok(str, sep);
  while(res != NULL){
     printf("Splitted String: \"%s\"\n",res);
     res = strtok(NULL,sep);
  }

  return 0;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, but you can ignore the newline by defining char sep[] = " \r\n"; and let strtok() do the work.
thanks for the solution, however, if the input is "I am" the output becomes "I am" no new line :/
@WeatherVane I mentioned it as that's a relevant fact to fgets() which is often a source of misunderstanding about fgets().
@Joel you still need to process the input string with strtok() and add a newline after every word. This answer is good because using scanf() will only read the first word of the sentence.
just updated the question with my current code. i cannot seem to get it to work with strtok(); It just prints out everything on the same row anyway.
|
2

That is not how scanf() works.

Change the code to

char str[100];
scanf("%s",str);

A little note about scanf()

You should check for return values, like here for scanf().

if (scanf("%s", str) != 1)
{
    printf("scanf failed");
    exit(0);
}


You should also mention the number of chars to be read by scanf() to avoid buffer overflow.

scanf("%99s", str)

For a char str[100] of size 100, one should give 99 to keep place for the null character \0.


6 Comments

So i cannot declare scanf immediately to str? i see.
You forget this '&' in your scanf?
@HemantParihar I don't need the & since it's already an array.
@Haris Thanks for the solution, I have a bad habit of overthinking stuff and trying to simplify my code by making several steps into one. Unfortunately it doesn't always work the way i want it to :) However, the output is just the first word. Any ideas on how i can get all of the results? Input: "I am" just prints out "I".
@Joel That's because scanf won't read multiple words. Use fgets() to read a whole line.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.