Hello..

Supposing that i have this code..i want it to end after a character is pressed..but i dont know what to add...i can end it if input is negative or zero..but not char..i tried some experiments but it will end up debug assertion fail..help would be great..

// adds numbers depending on user 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	vector<int> v;
	vector<int>::iterator it;
	
	int num,n,sum=0;
	cout<<"Enter series of numbers: ";cin>>num;
		while	(num > 0)
	{//here
		
		v.push_back(num);
		cin>>num;
	}
		
		cout<<"How many numbers to add: ";cin>>n;
		
		for(it = v.begin(); it < v.begin()+n ;it++)
		{
			sum+=*it;
		}
		cout<<"Sum of ";copy(v.begin(),v.begin()+ n ,ostream_iterator<int>(cout, ", "));
		cout<< "is "<<sum;

	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(),'\n');
	cin.get();
	return 0;
}

Try cin char, convert to number, if the conversion is OK, then push_back, if not, throw an error.

Try cin char, convert to number, if the conversion is OK, then push_back, if not, throw an error.

ive read about exceptions...if you throw, it will show an error right? i just want it to coontinue after i have entered the numbers except the char.

Then you don't throw an error, just put a break in the while.

ive tried it like this inside while..

if(num == static_cast<char>(s) )
{
break;
}

or

if(!cin)
{
break;
}

not working....either the program just stops or debug assertion fail

>>i want it to end after a character is pressed.

Use this :

vector<int> vec;
int n = 0;
//while user inputs a number, save it
while(cin >> n){ vec.push_back(n); }
 //now reset the stream
 cin.clear();
 cin.ignore(numeric_limits<streamsize>::max(),'\n'); 

 //now carry on with your code

>>i want it to end after a character is pressed.

Use this :

vector<int> vec;
int n = 0;
//while user inputs a number, save it
while(cin >> n){ vec.push_back(n); }
 //now reset the stream
 cin.clear();
 cin.ignore(numeric_limits<streamsize>::max(),'\n'); 

 //now carry on with your code

solved and satisfied..thanks firstPerson :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.