一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

实例1:忽略输入字符串的前面部分字符输出

 1 #include <iostream>  // 
 2 
 3 using namespace std;//名字空间 
 4 
 5 int main()
 6 {
 7       char buf[20];//只能存放19个字符,因为字符串以0结尾 
 8       
 9       cin.ignore(7);//忽略输入的前七个字符 
10       cin.getline(buf,10);//获取10个字符存放在buf中,默认字符串以0结尾 
11                  
12       cout<<buf<<endl;//endl表示清空缓存区 
13           
14       return 0;
15 }

实例2:打印输入的一段文本,回车结束

 1 #include <iostream>  // 
 2 
 3 using namespace std;//名字空间 
 4 
 5 int main()
 6 {
 7       char p;
 8       
 9       cout<<"请输入一段文本:\n";
10       
11       while(cin.peek()!='\n')//peek偷看输入的数据,不修改 
12       {
13               cout<<(p=cin.get());//cin.get表示获取输入的一个字符  
14       }
15       cout<<endl;//endl表示清空缓存区 
16           
17       return 0;
18 }

实例3:打印输入的前20个字符

 1 #include <iostream>  // 
 2 
 3 using namespace std;//名字空间 
 4 
 5 int main()
 6 {
 7       const int SIZE=50;
 8       char buf[SIZE];
 9       
10       cout<<"请输入一段文本:";
11       cin.read(buf,20);//读取20个字符到buf缓冲区中 
12       
13       cout<<"字符串收集到的字符数为:"<<cin.gcount()<<endl;//计算提取到的字符数 
14       
15       cout<<"输入的文本信息是:";
16       cout.write(buf,20); //从缓冲区输出20个字符 
17       
18       cout<<endl;//endl表示清空缓存区 
19           
20       return 0;
21 }

作业1:对3开方不同精度输出

 1 #include <iostream>  //
 2 #include <math.h> 
 3 
 4 using namespace std;//名字空间 
 5 
 6 int main()
 7 {
 8       double result=sqrt(3.0);
 9       
10       cout<<"对3开方保留小数点后0~9位,结果如下:\n\n"<<result;
11 
12       for(int i=0;i<=9;i++)
13       {
14               cout.precision(i);
15               cout<<result<<endl;
16        } 
17        cout<<"当前输出的精度为:"<<cout.precision()<<endl;          
18       return 0;
19 }

作业2:对于输入的字符串,每次提取其四个字符,以不同输出宽度输出

 1 #include <iostream>  //
 2 #include <math.h> 
 3 
 4 using namespace std;//名字空间 
 5 
 6 int main()
 7 {
 8       int width = 4;
 9       char str[20];
10       
11       cout<<"请输入一段文本:\n";
12       cin.width(5);//一次提取4个字符,因为最后有一个回车 
13 
14       while(cin >> str)
15       {
16               cout.width(width++);//设置不同的右对齐输出宽度 
17               cout<<str<<endl;
18               cin.width(5);
19        } 
20       return 0;
21 }
posted on 2023-08-18 14:00  一杯清酒邀明月  阅读(96)  评论(0编辑  收藏  举报