C语言题:自动对所有的整数进行求和并打印出结果

要求:

编写一个程序,要求用户输入一串整数和任意数目的空格,这些整数必须位于同一行中,但允许出现在改行中的任何位置。当用户按下键盘上的“Enter”键时,数据输入结束。程序自动对所有的整数进行求和并打印出结果。

注意:

scanf的返回值:返回成功读入的数据项数。

ungetc:作用是把一个(或多个)字符退回到stream代表的文件流中。

下面的代码中因为getchar()从输入流stdin中提取了一个字符,所以在后面ungetc中把刚提取的字符返回到输入流stdin中。

代码如下:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int i;
	int sum = 0;
	char ch;
	
	printf("请输入一串整数和任意数目的空格:");
	
	while ( scanf("%d", &i) == 1 )
	{
		sum += i;
		
		//getchar()在输入流stdin提取一个字符给了ch 
		while ( (ch=getchar()) == ' ')//屏蔽空格 
			;
		
		if ( ch == '\n' )
		{
			break;
		}
		
		ungetc(ch, stdin); //将变量ch中存放的字符退回给stdin 
	}
	
	printf("结果是: %d", sum);
	printf("\n");
	system("pause");

	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaodingqq/article/details/83443202
今日推荐