此代码会从用户接收未知数量的字符,直到他输入“;”然后打印一堆有关字符的信息。 我的问题是为什么扫描一个字符能够接收多个字符的输入,我认为一个字符的 scanf 仅适用于一个字符并且能够扫描多个字符我需要使用“%”扫描字符串或数组s”。
Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*=========================================================================
Constants and definitions:
==========================================================================*/
/* put your #defines and typedefs here*/
void printGivenParamsToTheOutput( char ch, int asciiCode, int asciiCodePowTwo,
int difference, int unitDigitOfDiff );
void printResults(int digitsCounter, int lettersCounter, int spacesCounter);
/*-------------------------------------------------------------------------
The main program. (describe what your program does here)
-------------------------------------------------------------------------*/
int main() {
char ch = 0;
int privNumChar=0, dif=0, lastDigDif=0, numDig=0, numLett=0, numSpac=0;
do {
scanf("%c", &ch); //asking for characters to analysis
if (ch == ';') { //';' ending the program running
break;
}
else {
// difference between current number to the previous one
dif = ch - privNumChar;
privNumChar = ch;
//calculating the difference last digit
lastDigDif = dif%10;
printGivenParamsToTheOutput(ch, ch, ch, dif, lastDigDif);
//calculating how many times each type appeared in the message
if (('a'<=ch && ch<='z') || ('A'<=ch && ch<='Z')) { ++numLett; }
else if ('0'<=ch && ch<='9') { ++numDig; }
else if (ch == ' ') { ++numSpac; }
}
}
while (ch != ';');
printResults(numDig, numLett, numSpac);
return 0;
}
void printGivenParamsToTheOutput (char ch, int asciiCode, int asciiCodePowTwo,
int difference, int unitDigitOfDiff){
asciiCodePowTwo = ch*ch; //calculating ascii value raising to a power
printf( "%c%10d%10d%10d%10d\n", ch, asciiCode, asciiCodePowTwo,
difference, unitDigitOfDiff );
}
void printResults(int digitsCounter, int lettersCounter, int spacesCounter){
printf("Number of digits received: %d\n", digitsCounter);
printf("Number of letters received: %d\n", lettersCounter);
printf("Number of spaces received: %d\n", spacesCounter);
}
你有
do {
scanf("%c", &ch); //asking for characters to analysis
//some further code
while (ch != ';');
现在,您正在重复将字符读入
ch
,直到;
的结束符号。您不是通过一次 scanf
调用来完成此操作,而是重复调用它,直到收到 ;
的结束信号。
尝试调试代码并查看每次
ch
会遇到什么情况,然后您会发现您关于 scanf
每次调用 char
接收单个 %c
的假设得到遵守。