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

时间:2012-10-07 10:13:47

标签: c

我正在编写代码并需要一些帮助。

需要从文件中读取一行。必须忽略第一个单词,并且必须将剩余的字符(包括空格)存储到变量中。我该怎么做?

2 个答案:

答案 0 :(得分:2)

如果您的单词前面没有空格并且您使用空格('')作为分隔符,则此方法将有效。

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

答案 1 :(得分:0)

一些例子。阅读程序中的注释以了解效果。这将假设单词由空白字符(由isspace()定义)分隔。根据您对“单词”的定义,解决方案可能会有所不同。

#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;
}
相关问题