0

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

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

4

2 回答 2

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;
}
于 2012-10-07T14:30:01.363 回答
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;
}
于 2012-10-07T11:36:11.533 回答