屏幕输入流中的空格,讲输入流中的数求和
C语言实现
#include <stdio.h>
#include <cstdio>
int main()
{
int sum = 0;
int i;
int ch;
printf("Please input some number and blank point:\n");
while ((scanf("%d",&i))==1)
{
sum += i;
while ((ch = getchar()) == ' '); //屏蔽空格
if (ch == '\n') {
break;
}
ungetc(ch, stdin); //将ch吃掉的数字吐出给输入流
}
printf("The sum is:%d", sum);
return 0;
}
C++实现
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
int i;
cout << "Please input some numbers and blank point:\n";
while (cin >> i) {
sum += i;
while (cin.peek() == ' ') {
cin.get(); //从输入流中流走一个字符,这里是" "
}
if (cin.peek() == '\n') {
break; //因为cin遇到enter时返回值不为flase 所以要另写程序控制当enter时停止输入
}
}
cout << "The result is:" << sum << endl;
return 0;
}
粗略讲讲某些cin函数
cin.get() 没有参数 , 让输入流中白流走一个字符
cin.get(数组名,字节数n) 遇到enter会停止,最终数组只得到n-1个字符,可存空格
cin.getline(数组名,字节数n,结束字符) 没有第三个参数时默认为enter结束,最终数组得到n-1个字符,可存空格
cin.ignore(字节数)屏蔽输入流中n个字符
cin.peek() 将输入流中的一个字符捡起来作为返回值,以用用来检查,peek捡起后会主动放回不需要ungetc(这是和getchar的区别)