从一个小程序说起(2)
要求:编写一个程序:要求用户输入遗传整数和任意数目的空格,将这些位于一行的整数累加求和,并输出。
C代码:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int i;
int sum = 0;
char ch;
printf("please input a serise of number and space:");
while (scanf_s("%d", &i) == 1)
{
sum += i;
while ((ch = getchar()) == ' ')
; //屏蔽空格
if (ch == '\n')
{
break;
}
ungetc(ch, stdin);//将变量ch中存放的字符退回给stdin输入流(数组或者链表)
}
printf("the result is:%d",sum);
printf("\n");
system("pause");
}
Cpp代码:
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
cout<<"请输入一串整数和任意数目的空格:";
int i;
while (cin >> i)
{
sum += i;
while (cin.peek() == ' ')
{
cin.get();
}
if (cin.peek() == '\n')
{
break;
}
}
cout << "结果是:" << sum << endl;
return 0;
}
–这个程序使用了cin。这个对象的类型是iostream,他知道如何从用户终端读取数据
–cin>>i;cin输入操作符又称为提取操作符,他一次从输入流对象cin中提取一个整数;
–阻塞:如果用户不进行键盘的输入,程序将会阻塞blocking
–>>最初是右移操作符,后被Cpp重载;另外,这个操作符对所有内建的数据类型都进行了重载,所以他可以从输入流中提取出int,float,double型数据,也可以提取出字符串等数据;
–cin.ignore与cin.getline
#include<iostream>
using namespace std;
int main()
{
char buf[20];//only write 19 numbers
cin.ignore(7);//忽略前七个字符
cin.getline(buf, 10);//保留10个位置,其中最后一个要以0结尾,表示第十个位置,这是因为字符串的缘故
cout << buf << endl;
system("pause");
return 0;
}
–cin.get()与cin.peek()
#include<iostream>
using namespace std;
int main()
{
char p;
cout << "请输入一段文本:\n";
while (cin.peek() != '\n')
{
p = cin.get();
cout <<p;
}
cout << endl;
system("pause");
return 0;
}
–cin.gcount()与cin.read()
#include<iostream>
using namespace std;
int main()
{
const int SIZE = 50;//类似于宏定义,但要比宏定义好很多
char buf[SIZE];
cout << "请输入一段文本:";
cin.read(buf, 20);
cout << "字符串收集到的字符数为:"
<< cin.gcount() << endl;
cout << "输入的文本信息是:";
cout.write(buf, 20);
cout << endl;
system("pause");
return 0;
}
–cin.precision()
#include<iostream>
using namespace std;
int main()
{
double result = sqrt(3.0);
cout << "对3开方保留0~9位有效数字,结果如下:\n" << endl;
for (int i = 0; i <= 9; i++)
{
cout.precision(i);
cout<<result<< endl;
}
cout << "当前的输出有效数字为:" << cout.precision() << endl;
system("pause");
return 0;
}
–cin.width()
#include<iostream>
using namespace std;
int main()
{
int width = 4;
char str[20];
cout << "请输入一段文字:\n";
cin.width(5);
while (cin >> str)
{
cout.width(width++);
cout << str << endl;
cin.width(5);
}
return 0;
}