制御文のサンプルプログラム
今日は『Objective-Cの絵本』の第2章の最後にある
制御文のサンプルプログラムを作成しました。
以下引用『Objective-Cの絵本』P44より。
#include <stdio.h>
int main(int argc, const char * srgv[])
{
char c = '\0'; /*キーボードから入力した文字*/
char firstletter; /*最初の文字をとっておきます*/
int wordnum; /*単語の文字数*/
int word_in; /*単語に入っていれば1、そうでない場合は0*/
while (1)
{
wordnum = 0;
word_in = 1;
firstletter = '\0';
printf("文字列を入力してください;");
while (1)
{
c = getchar();
if(c == '\n')
{
if (word_in)
wordnum++;
break;
}
firstletter = c;
if (c == ' ' || c == '.')
{
if (word_in)
{
wordnum++;
word_in = 0;
}
}
else
word_in = 1;
}
if (firstletter == '\0')
break;
printf("ワード数:%d\n", wordnum);
}
return 0;
}
単語と単語のあいだにあるスペースまたはピリオドで単語数をカウントしていく
しくみなのですが、プログラムの一行一行の意味をYahoo知恵袋などで調べながら
なんとか理解。時間がかかりました…。
たとえば「while(1)」がなぜ無限ループなのかがわからなったのですが、
こちらに答えがありました。
c言語の質問です 本を見ていて、「while(1)」 と言う文字が出てきたのですが、ルー... - Yahoo!知恵袋
めげずにがんばります!