✅ Task:
Read a text, and turn it into a number. If this does not work, say "Bad String."
🧠 Idea:
Use error checks (try-catch) in C++ to deal with errors in turning text to a number.
📥 Input:
Just one text S.
📤 Output:
Show the number if the text is okay.
If not, say "Bad String".
✅ Good Input:
yaml
Copy
Edit
1234
✅ Good Output:
yaml
Copy
Edit
1234
❌ Bad Input:
nginx
Copy
Edit
abc
❌ Bad Output:
arduino
Copy
Edit
Bad String
✅ C++ Way to do it:
cpp
Copy
Edit
#include <iostream>
#include <string>
using namespace std;
int main() {
string S;
cin >> S;
try {
int number = stoi(S); // std::stoi throws if it can't change the text
cout << number << endl;
} catch (...) {
cout << "Bad String" << endl;
}
return 0;
}
📝 Tips:
stoi() gives invalid_argument if the text can't be turned.
You can catch (exception &e) or catch (...) to get all errors.
This helps you learn how to deal with bad inputs and error checks in C++.
Comments
Post a Comment