Jack Jackson
Jack Jackson

Reputation: 87

Ignore first word from the line in c

I am working on a code and need some help.

There is a line which needs to be read from a file. The first word must be ignored and the remaining characters (white spaces included) have to be stored into variable. How do I do it?

Upvotes: 0

Views: 2119

Answers (2)

max.haredoom
max.haredoom

Reputation: 878

This will work if your word has no spaces in front of it and you use white space (' ') as separating character.

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

int main()
{
    char buffer[80];
    char storage[80];
    fgets(buffer, 80, stdin); // enter: »hello nice world!\n«
    char *rest = strchr(buffer, ' '); // rest becomes » nice world!\n«

    printf("rest:   »%s«\n", rest); // » nice world!\n«
    printf("buffer: »%s«\n", buffer); // »hello nice world!\n«

    strncpy( storage, rest, 80 ); // storage contains now » nice world!\n«
    printf("storage: »%s«\n", storage); // » nice world!\n«

    // if you'd like the separating character after the "word" to be any white space
    char *rest2 = buffer;
    rest2 += strcspn( buffer, " \t\r\n" ); // rest2 points now too to » nice world!\n«
    printf("rest2:  »%s«\n", rest2); // » nice world!\n«

    return 0;
}

Upvotes: 2

nhahtdh
nhahtdh

Reputation: 56809

Some examples. Read the comments in the program to understand the effect. This will assume that words are delimited by whitespace characters (as defined by isspace()). Depending on your definition of "word", the solution may differ.

#include <stdio.h>

int main() {
    char rest[1000];
    // Remove first word and consume all space (ASCII = 32) characters
    // after the first word
    // This will work well even when the line contains only 1 word.
    // rest[] contains only characters from the same line as the first word.
    scanf("%*s%*[ ]");
    fgets(rest, sizeof(rest), stdin);
    printf("%s", rest);

    // Remove first word and remove all whitespace characters as
    // defined by isspace()
    // The content of rest will be read from next line if the current line
    // only has one word.
    scanf("%*s ");
    fgets(rest, sizeof(rest), stdin);
    printf("%s", rest);

    // Remove first word and leave spaces after the word intact.
    scanf("%*s");
    fgets(rest, sizeof(rest), stdin);
    printf("%s", rest);

    return 0;
}

Upvotes: 0

Related Questions