In: Computer Science
using this code under, I want when the user input only letter q an error message appears that there is no second smallest, how I can do that?
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int secondSmallestNumber(vector<int> &I);
int main() {
cout << "Enter the numbers in random order: (close by entering q)" << endl;
vector<int> I;
int input;
stringstream ss;
string str;
bool flag = false;
while (!flag) {
getline(cin, str);
ss.clear();
ss << str;
while (ss >> input || !ss.eof()) {
if (ss.fail()) {
flag = true;
break;
}
I.push_back(input);
}
}
int result;
try {
result = secondSmallestNumber(I);
cout << "The second smallest number is: " << result << endl;
}
catch (const runtime_error& e ) {
cout << "error: no second smallest" << endl;
}
return 0;
}
int secondSmallestNumber(vector<int> &I){
std::sort(I.begin(), I.end());
int number = I.at(0);
for (int i = 0; i < I.size() - 1; i++) {
if (I.at(i + 1) > number) {
return I.at(i + 1);
}
}
throw runtime_error("error");
}
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include<stdexcept>
using namespace std;
int secondSmallestNumber(vector<int> &I);
int main() {
cout << "Enter the numbers in random order: (close by entering q)" << endl;
vector<int> I;
int input;
stringstream ss;
string str;
bool flag = false;
getline(cin, str);//ask outside while loop
if(str == "q"){// check if starting character is q
cout<<"there is no second
smallest";
return 0;
}
while (!flag) {
getline(cin, str);
ss.clear();
ss << str;
while (ss >> input || !ss.eof()) {
if (ss.fail()) {
flag = true;
break;
}
I.push_back(input);
}
}
int result;
try {
result = secondSmallestNumber(I);
cout << "The second smallest number is: " << result << endl;
}catch(const runtime_error& e ) {
cout << "error: no second smallest" << endl;
}
return 0;
}
int secondSmallestNumber(vector<int> &I){
std::sort(I.begin(), I.end());
int number = I.at(0);
for (int i = 0; i < I.size() - 1; i++) {
if (I.at(i + 1) > number) {
return I.at(i + 1);
}
}
throw runtime_error("error");
}
/* OUTPUT */
/* PLEASE UPVOTE */