C++——peek()一个带空格整型字符串的相加

getchar()函数:从键盘输入流获得一个字符。
作用之一:屏蔽空格

char ch;
while((ch=getchar()=='');//屏蔽空格

ungetc(ch,stdin);//将变量ch中存放发字符退回给stdin输入流。
例子:输入一串整数和空格的字符串,以空格隔开的为一个独立整数,将其进行累加。
c语言实现

#include<stdlib.h>
#include"stdio.h"
int main()
{
    int i;
    int sum =0;
    char ch;
    printf("请输入一个含有整数和空格的字符串:");

    while(scanf("%d",&i)==1)
    {

        sum +=i;
        while((ch =getchar())==' ');
        if(ch == '\n')
        {
            break;
        } 
        ungetc(ch,stdin);
    }
    printf("result=%d\n",sum);
    system("pause");
    return 0;
}

结果

c++语言实现

int main()
{
    int sum =0;
    cout<<"请输入一个含有整数和空格的字符串:";
    
    int i;
    while(cin>>i)
    {
        sum += i;
        while(cin.peek() ==' ')//屏蔽空格,将空格输入到输入流
        {
            cin.get();//输入空格字符到输入流
        }
        if(cin.peek() =='\n')
        {
            break;
         }
      }
      cout <<"result ="<<sum<<endl;
      return 0;
 }
     

结果

发布了59 篇原创文章 · 获赞 14 · 访问量 4307

猜你喜欢

转载自blog.csdn.net/weixin_38251305/article/details/104216761
今日推荐