Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input string without using C++ string

I was asked to take a string (which can be of any size ) from input without using C++ string. I thought of dynamically allocating space for a char array and got following implementation from SO itself. But I am not sure whether it is a good implementation. Is there a better implementation for this which doesn't require you to input the number of elements in the name?

#include<iostream>
int main()
{
    int size = 0;
    std::cout << "Enter the size of the dynamic array in bytes : ";
    std::cin >> size;
    char *ptr = new char[size];

    for(int i = 0; i < size;i++)
        std::cin >> *(ptr+i);
}
like image 678
Sumit Gera Avatar asked Mar 28 '26 01:03

Sumit Gera


1 Answers

Possibly bending the rules (or I don't understand the question, but...). Anyway, when someone says "dynamic array" with C++, I naturally think of a vector.

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
    vector<char> vec;
    copy(istreambuf_iterator<char>(cin),
         istreambuf_iterator<char>(),
         back_inserter(vec));
    vec.push_back(0);
    cout << vec.data() << endl;
    return 0;
}

Think that will do it.


The short version

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
    vector<char> vec {istreambuf_iterator<char>(cin),
                      istreambuf_iterator<char>()} ;
    vec.push_back(0);
    cout << vec.data() << endl;
    return 0;
}
like image 173
WhozCraig Avatar answered Mar 29 '26 14:03

WhozCraig