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);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With