I want to get unlimited chars, actually I created char*, I use cin for it, and I want to change it to string. I don't know the length of the input which user enters, so I made this solution for myself. Can someone tell me plz, how to get a char* without knowing the size of input and converting to string. thanks.
Asked
Active
Viewed 1,259 times
-3
-
6Why don't you just use `std::string`? – UnholySheep Jun 28 '17 at 12:21
-
You could create a linked list. But that's way less efficient over time than what std::string does, which is hold some buffer that begins at an initial size, and then reallocates a larger buffer when it gets too big. – AndyG Jun 28 '17 at 12:23
-
Actually I Want another solution , not getting string, I wanna solve my problem in getting unlimited char,is there anyway except linkedlist? – Zahra Jun 28 '17 at 12:29
-
1@Zahra Alternatively you could use a `std::unique_ptr
s(new char[arbitrary_length]);`. But you would need to manage the NUL termination yourself, and still know a maximum length before taking input. The better way is to simply use `std::string`. – πάντα ῥεῖ Jun 28 '17 at 12:31 -
If you don't want to use `std::string` then you have to implement the functionality of `std::getline` yourself. Maybe you could copy the source to your project and tinker with it. – Dialecticus Jun 28 '17 at 12:44
2 Answers
5
Since it is C++. Just use std::string
If you really need to use char*
look at this topic

Petar Velev
- 2,305
- 12
- 24
2
Instead of using a char *
, use the standard library.
#include <string>
#include <iostream>
int main()
{
std::string data;
std::getline(std::cin, data);
std::cout << data << '\n';
}
This will read a string of any length (at least, until a newline is entered, which will not be included in data
) and then print it out.
You might wish to also check the state of std::cin
to test if any errors occurred.

Peter
- 35,646
- 4
- 32
- 74
-
Thank you a lot @Peter , but actually I'm searching for the way which I can get char. thank you for your reply! – Zahra Jun 28 '17 at 12:33
-
1@Zahra - Read the documentation for `std::string`. It has member functions that provide access to the underlying data ..... as a pointer to (the first element of) a dynamically allocated array of `char` i.e. a `const char *`. If you try to work with a raw pointer (instead of `std::string`), you'll need to manually manage the memory allocation and (just as importantly) deallocation when you no longer need it. – Peter Jun 28 '17 at 12:38