编写一个程序

问题描述:

编写一个程序,要求用户输入一串整数和任意数目的空格,

这些整数必须位于同一行中,但允许出现在该行中的任何位

置。当用户按下键盘上的“Enter”建时,数据输入结束。程序

自动对所有的整数进行求和并打印出结果。


c语言版本:(程序来源网上)

#include <stdio.h>
#include <stdlib.h>

void main()
{
      int i;
      int sum = 0;
      char ch;

      printf("Please input a string of integers and arbitrary 

number of spaces: ");

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

            while( (ch=getchar()) == ' ' )
                  ;
            if( ch == '\n' )
            {
                  break;
            }

            ungetc( ch, stdin );
      }

      printf("The result is: %d", sum);
      printf("\n");
      system("pause");
}


c++版本:(程序来源网上)

#include <iostream>

using namespace std;

int main()
{
      int sum = 0;

      cout << "Please input a string of integers and 

arbitrary number of spaces:"<<endl;
      int i;
      while( cin >> i )
      {
            sum += i;
            while( cin.peek() == ' ' )
            {
                  cin.get( );
            }
            if( cin.peek( ) == '\n' )
            {
                  break;
            }
      }
      cout <<"The result is:"<<sum<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值