1行のファイルがあります.Linuxでは、デフォルトで改行で終わります
one two three four
そして、同様のもの
one five six four
間にある 2 つの単語が「4」にならないことが保証されています。このコードのように、「ツー スリー」と「ファイブ シックス」を変数に代入したいので、次のように書きました。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool getwords(FILE *example)
{
bool result = 0;
char *words;
if(fscanf(example, "one %s four\n", words) == 1)
{
printf("captured words are %s\n", words);
if(words == "two three"
|| words == "five six")
{
puts("example words found");
}
else
{
puts("unexpected words found");
}
result = 1; //so that we know this succeeded, in some way
}
return result;
}
int main(int argc, char * argv[])
{
if(argc != 2)
{
exit(0);
}
FILE *example;
example = fopen(argv[1],"r");
printf("%x\n", getwords(example)); //we want to know the return value, hex is okay
fclose(example);
return 0;
}
問題は、これが "captured words are " を出力し、2 つの単語のうち最初の単語だけが文字列として期待されることです。これは、単語「one」と「four」の間に 2 より多くの単語が存在する可能性があるファイルをサポートすることになっています。コードを変更して、文字列内の最初の単語と最後の単語の間のすべての単語を取得するにはどうすればよいですか?