私はコードに取り組んでいて、助けが必要です。
ファイルから読み取る必要のある行があります。最初の単語は無視する必要があり、残りの文字(空白を含む)は変数に格納する必要があります。どうすればいいのですか?
私はコードに取り組んでいて、助けが必要です。
ファイルから読み取る必要のある行があります。最初の単語は無視する必要があり、残りの文字(空白を含む)は変数に格納する必要があります。どうすればいいのですか?
これは、単語の前にスペースがなく、区切り文字として空白 (' ') を使用している場合に機能します。
#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;
}
いくつかの例。プログラム内のコメントを読んで、効果を理解してください。これは、単語が空白文字で区切られていることを前提としています ( で定義されています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;
}