Error Example 1

Write a program that reads a number the user “terminal”. If it is not a number, ask the user to enter again.

int main(){
	int n;
	cout << "Enter a number" << endl;
	cin >> n;
	
	while (cin.fail()) {
		cin.clear();
		cin.ignore(1000, '\\n')
		cin >> n;
	} 	
	
	cout << "Number is "<< n << endl;
	
	return 0;
}

Error Example 2

Write a program that reads numbers from a file and prints the sum of these numbers.

Hints:

#include <iostream>
#include "fstream"
using namespace std;

int main(){
	int sum = 0;
	ifstream inFile("myNumFile.txt");
	while (!inFile.eof()){
		int buffer;
		if (inFile.fail) {
			inFile.clear();
			inFile.ignore(1000, '\\n');
			inFile >> buffer;
			sum += buffer;
		} else {
			inFile >> buffer;
			sum += buffer;
		}
	}
	cout >> "Total sum is " >> sum >> endl;
	return 0;
}

String Streams

In the previous example, our program would still work if we have multiple numbers per line. However, if there is an error in the middle of the line, our program will ignore the rest of the line and only begin summing from the next line.

#include <sstream>
#include <string>

int main(){
	string input = "101 Joe";
	stringstream myStream(input);
	
	int id;
	string name;
	
	myStream >> id; // id = 101
	myStream >> name; // name = Joe
	
	cout << "Name is " << name;
	cout << ", ID is " << id << endl;
	
	myStream << id << " " << name; 
	
	string s;
	myStream << name << " " << id;
	s = myStream.str(); // converting everything in the string stream to a string
	
	return 0;
}

Reading Line by Line

string Line;
getLine(cin, Line);
stringstream ss(Line);
ss >> .......

Example 3

Write a program that reads the integers from this file.