Skip to main content

Featured

say hello world with C++ - Solution in Hacker Rank - hackerranksolutions8

  Objective This is a simple challenge to help you practice printing to  stdout . You may also want to complete  Solve Me First  in C++ before attempting this challenge. We’re starting out by printing the most famous computing phrase of all time! In the editor below, use either  printf  or  cout  to print the string  Hello ,World!  to  stdout . The more popular command form is  cout . It has the following basic form: cout<<value_to_print<<value_to_print; Any number of values can be printed using one command as shown. The  printf  command comes from C language. It accepts an optional format specification and a list of variables. Two examples for printing a string are: printf("%s", string);   printf(string); Note that neither method adds a newline. It only prints what you tell it to. Output Format Print   Hello ,World!   to stdout. Sample Output Hello, World! Solution:- //Say Hello, ...

StringStream in C++ – Solution in Hacker Rank - hackerranksolutions8

 

Problem

stringstream is a stream class to operate on strings. It basically implements input/output operations on memory (string) based streams. stringstream can be helpful in different type of parsing. The following operators/functions are commonly used here

  • Operator >> Extracts formatted data.
  • Operator << Inserts formatted data.
  • Method str() Gets the contents of underlying string device object.
  • Method str(string) Sets the contents of underlying string device object.

Its header file is sstream.

One common use of this class is to parse comma-separated integers from a string (e.g., “23,4,56”).

stringstream ss("23,4,56");
char ch;
int a, b, c;
ss >> a >> ch >> b >> ch >> c;  // a = 23, b = 4, c = 56

You have to complete the function vector parseInts(string str)str will be a string consisting of comma-separated integers, and you have to return a vector of int representing the integers.Note If you want to know how to push elements in a vector, solve the first problem in the STL chapter.


Input Format :

The first and only line consists of n integers separated by commas.

Output Format :

Print the integers after parsing it.
P.S.: I/O will be automatically handled. You need to complete the function only.


Sample Input :

23,4,56

Sample Output :

23
4
56

Solution :-

//StringStream in C++ - Hacker Rank Solution
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;

vector<int> parseInts(string str) 
{
	// Complete this function
    stringstream ss(str);
    vector<int> result;
    char ch;
    int tmp;

    while (ss >> tmp) 
    {
        result.push_back(tmp);
        ss >> ch;
    }

    return result;
}

int main() 
{
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) 
    {
        cout << integers[i] << "\n";
    }
    
    return 0;
}

Comments