1.知识点
①利用C库里面的ungetc()函数可以将getchar()取出的字符回退到输入流中,注意利用ungetc()要include stdio.h库
②ungetc()函数详解
http://codingdict.com/article/2266
③stdin,为cin的输入流
2.用法:
①当输入流为文件时:
http://codingdict.com/article/2266
https://www.xuebuyuan.com/1197103.html
注意点:
ungetc 不能连续多次调用。两次 ungetc 调用之间必须至少有一次读操作或者文件指针移动操作(fseek,rewind 等 ) , ungetc 只影响输入流,而不影响与输入流关联的外存文件。对于以二进制方式打开的流,ungetc 会使读指针减 1 ,如果当前位置为 0 ,则减 1 后结果 无法预测。紧跟在 fscanf 后面的 ungetc 也可能会失败,因为 fscanf 中就用到了 ungetc。
②当输入流为cin即 stdin时
<1>text
#include<iostream>
#include <stdio.h>
using namespace std;
int main()
{
char b=getchar();//输入一个字符在缓冲区并且存入b
ungetc(b,stdin);//将b回退到stdin输入流
int c;
cin>>c;//上一个回退的,给现在继续存入到c
cout<<c<<endl;
}
<2>例题:
编写程序,在被调函数中删去一维数组中所有相同的数,使之只剩一个,数组中的数已按由小到大的顺序排列,被调函数返回删除后数组中数据的个数。
例如:
原数组:2 2 2 3 4 4 5 6 6 6 6 7 7 8 9 9 10 10 10
删除后:2 3 4 5 6 7 8 9 10
代码:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"请输入原数组:";
int flag,element;
char END;
cin>>flag;//存进第一个元素
int count=1;//记录删除后数组的元素个数
while(END!='\n')//当读取到最后一个元素即回车符时,跳出循环
{
cin>>element;//原数组元素
if(element!=flag){//如果元素改变,则计数+1
count++;
flag=element;
}
END=getchar();
if(END!='\n'){
ungetc(END,stdin);//当字符不是回车时,将数字回退到输入流stdin中
}
}
cout<<"删除重复后的数组的个数为:"<<count<<endl;
}