简体   繁体   English

忽略c中该行的第一个单词

[英]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? 我该怎么做?

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;
}

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() ). 这将假设单词由空格字符(由isspace()定义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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM