小甲鱼《C++快速入门》笔记(三)从一个小程序说起(2)

从一个小程序说起(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;

	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值