10/03/2017

Hacker Rank Solution For Day 16: Exceptions - String to Integer

Problem:- Write a Hackerrank Solution For Day 16: Exceptions - String to Integer or Hacker Rank Solution Program In C++ For " Day 16: Exceptions - String to Integer " or Hackerrank 30 days of code Java Solution:Day 16: Exceptions - String to Integer solution or Hackerrank solution for 30 Days of Code Challenges or Hackerrank 30 days of code Java Solution, Day 16: Exceptions - String to Integer solution, or C/C++ Logic & Problem Solving: Day 16: Exceptions - String to Integer or Hacker Rank Solution For Day 16: Exceptions - String to Integer

Check This:- Hacker rank solution for Strings, Classes, STL, Inheritance in C++.



Hacker Rank Solution For Day 16: Exceptions - String to Integer

Logic:- There is no logic for this problem we have to use try-catch block(same as Java) as we know if the condition in the try block is true then the program is working fine else catch part will be executed. In this problem, we are taking a string input and printing its string value or string can't be converted then it should print Bad String that is why we use Try Catch block if program convert string into integer then it is Ok. if not than Catch block will be executed and we put a message on catch block.

stoi - The stoi() function takes a string as an argument and returns its value.

Syntax of Try-Catch

try
{
statement......1
statement......2
statement......3
.
.
.
statement......n
}
catch(exception )
{
statements //message
}

Also Check:- Geeksforgeeks solution for School, Basic, Easy, Medium, Hard in C++.

Basically, Try- catch is used in a runtime error in a program. Read full about Try-Catch click here


Submit Your Solution Here:- Click Here

Solution:-

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int main()
{
    string S;   
    cin >> S;
    
    int n;

    try
    {
        n=stoi(S);
        cout<<n<<endl;
    }
    catch(exception e)
    {
        cout<<"Bad String";
    }
    return 0;
}

Output:-


Hacker Rank Solution For Day 16: Exceptions - String to Integer


You May Also Like:-

1. Hackerrank Solution For Day 12: Inheritance

2. Hackerrank Solution For Day 13: Abstract Classes

3. Hackerrank Solution For Day 14: Scope

4. Hackerrank Solution For Day 15: Linked List

5. Hackerrank Solution For Day 17: More Exceptions

6. Hackerrank Solution For Day 18: Queues and Stacks

7. Hackerrank Solution For Day 19: Interfaces

8. Hackerrank Solution For Day 20: Sorting

9. Hackerrank Solution For Day 21: Generics


10. Hackerrank Solution For Day 22: Binary Search Trees


No comments:

Post a Comment