Printing out word by word using pointers

Viewed 503

I am trying to make a program that prints out a sentence word by word using a pointer. I am having hard time finding the problem.

    char str[100];
    char *p;

    printf("\nSentence: ");
    scanf("%s", str);

    p=str;

    while(*p!='\0'){
        if(*p == ' '){
            printf("\n");
        }else{
            printf("%c", *p);
        }
        p++;
    }
5 Answers

You can use gets_s instead of scanf("%s"):

gets_s(str, sizeof(str));

Then you code will work fine.

scanf("%s") will get only one word from standard input.

On the other hand, gets_s will get a whole line.

But gets_s() can work only on Visual Studio, in order to make it portable, it's better to use fgets().

Using of the function scanf with the format "%s" skips leading white spaces and reads characters until a white space is encountered.

So you can not enter a sentence using this format,

Instead use the standard function fgets.

Moreover take into account that the user can separate words with several spaces or tabs. In this case your output will be invalid because there will be many empty lines.

It is more efficient to use the standard C functions strspn and strcspn.

Here is a demonstrative program.

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

int main(void) 
{
    enum { N = 100 };
    char str[N] = "";

    printf( "Enter a Sentence: " );

    fgets( str, N, stdin );

    str[ strcspn( str, "\n" ) ] = '\0';

    const char *p = str;

    const char *delim = " \t";

    while ( *p )
    {
        p += strspn( p, delim );

        const char *q = p;

        p += strcspn( p, delim );

        if ( p != q )
        {
            printf( "%*.*s\n", ( int )( p - q ), ( int )( p - q ), q );
        }
    }

    return 0;
}

If for example to enter the following statement

Have a nice day Luka Milicevic

then the program output will be

Enter a Sentence: Have a nice day Luka Milicevic
Have
a
nice
day
Luka
Milicevic

scanf will read until first whitespace ,so only first word will be stored in str.

use fgets instead of scanf:(using fgets is a safe way)

#include <stdio.h>

int main()
{
    char str[100];
    char* p;

    printf("\nSentence: ");
    fgets(str, 100, stdin);
    p = str;

    while (*p != '\0') {
        if (*p == ' ') {
            printf("\n");
        }
        else {
            printf("%c", *p);
        }
        p++;
    }
    return 0;
}

scanf reads the string until the first whitespace. If you input a sentence like 'first second', only 'first' will be read. To read a full line, you should use fgets.

Try to avoid using gets, as it doesn't limit the number of characters to read, which could cause a security vulnerability.

You could also use scanf like

scanf("%99[^\n]", str);

It will read any non '\n' (line ending) character upto max 99 so your buffer won't overflow.

Although using fgets is a safer bet.

Related