C / C ++ read char * input of unknown length

I want to know if a line of unknown size can be read until a new line is reached. What I did in C ++ is:

char * dynStr;
char buffer[20];

cin >> buffer;
dynStr = new char[strlen(buffer) +1];
strcpy(dynStr, buffer);

But the problem is, what if the input you enter is greater than 20? So I think it should be something like this:

do
{
 cin.get ( buffer, 20, ' '); //im not sure this is the right approach
 strcpy(.....); // if is not  a first iteration 
 //add the new buffer to the  end of dyn str..
} while( ! read ' ' or '\n' ) <--- this is what I have problem doing

I know in C ++, I can use std::string, but I would like to know how to do this, so if you have any ideas, tell me :)

+4
source share
1 answer

get()and several other methods, you can only read until one specific character is read. You want to read until a new line or space is received.

For a simple situation like this, it's best to just use

cin.get();

, , . peek();.

, excersize . read() , , newline, , , .

, , .

+2

Source: https://habr.com/ru/post/1659821/


All Articles