Sum of integers separated by spaces

Question requirements: Enter a number of integers, each of which can be separated by a number of spaces, and write a program to achieve the sum of these integers.
Analysis: At first glance, it looks very simple, but when I actually operate it, I found out that there is a hidden murder! How can I accurately recognize the input stop when I don’t know how many integers there are? How to deal with a certain number of spaces? All need a certain amount of knowledge reserve
. On the code:

#include<iostream>
using namespace std;
int main(){
    
    
	int sum=0;
	cout<<"请输入一串以任意数目空格隔开的若干整数:";
	int i;
	while(cin>>i){
    
    
		sum+=i;//了解 cin>> 的功能:自动以空格为依据提取出来输入的整数(提取操作符)
		while(cin.peek()==' '){
    
    //检测到输入空格,用接下来的语句(cin.get())忽略掉空格
			cin.get();
		}
		if(cin.peek()=='\n')//检测到换行符,跳出循环
			break;
	}
	cout<<sum<<endl;
	return 0;
}

Another way of writing is similar with little difference:

#include<iostream>
using namespace std;
int main(){
    
    
	int sum=0;
	cout<<"请输入一串以任意数目空格隔开的若干整数:";
	int i;
	while(cin.peek()!='\n'){
    
    //将循环结束条件放在开头
		cin>>i;
		sum+=i;
		while(cin.peek()==' '){
    
    
			cin.get();
		}
	}
	cout<<sum<<endl;
	return 0;
}

Therefore, we have solved the problem and answered the above questions:
1. Determine whether the input is stopped by judging whether there is a newline character
. 2. The processing of spaces is ignored by the cin.get() statement

Guess you like

Origin blog.csdn.net/interestingddd/article/details/114809681