それはあなたのプログラムで使用されているようscanf
機能は安全ではありませんし、空白をカウントすることはできません。
注意。
scanf("%s",str);
^^^
そして、C標準関数mainに応じて、パラメータを指定せずに書くことはなく、
scanf("%s",&str);
^^^
が、それは正しいだろう考慮に入れる
int main(void)
のように宣言されなければなりません機能を使う方が良いです。fgetc
この
Hi, Marco Roberts
Welcome to SO
のようなテキストを入力する場合は、プログラムの出力は
space: 4
tabs: 0
new line: 2
使用はCtrl + zまたはCtrlキー+ Dを(応じて次のようになります
#include <stdio.h>
int main(void)
{
unsigned int space = 0;
unsigned int tabs = 0;
unsigned int newLine = 0;
printf("Enter the text: ");
int c;
while ((c = fgetc(stdin)) != EOF)
{
switch (c)
{
case ' ':
++space;
break;
case '\t':
++tabs;
break;
case '\n':
++newLine;
break;
}
}
printf("\nspace: %u\ntabs: %u\nnew line: %u\n", space, tabs, newLine);
return 0;
}
たとえば、使用しているシステムで)入力を中断します。
別のアプローチは、これをチェックするより良い方法は、ASCII値を比較することで、次のよう
#include <stdio.h>
#define N 100
int main(void)
{
unsigned int space = 0;
unsigned int tabs = 0;
unsigned int newLine = 0;
printf("Enter the text: ");
char str[N];
while (fgets(str, sizeof(str), stdin))
{
for (const char *p = str; *p; ++p)
{
switch (*p)
{
case ' ':
++space;
break;
case '\t':
++tabs;
break;
case '\n':
++newLine;
break;
}
}
}
printf("\nspace: %u\ntabs: %u\nnew line: %u\n", space, tabs, newLine);
return 0;
}
私はファイルの代わりにコンソールから入力を取得したいのですが? @xing –
getchar()を使用できますか?はいの場合は、どうですか?なぜなら、私はそれを試してみましたが、正しい出力を与えていないからです。 –
助けてくれてありがとうございました。 –