Answer the question
In order to leave comments, you need to log in
How to write a character-by-character input function that returns the entered string?
Please help me implement a function that reads the input character by character until it reaches the end of the input or a newline character is encountered. The function should return a C-style string with the characters read.
Tried like this:
char* getline()
{
char in;
int i=0;
char* pOld = new char[1];
char* pNew = new char[1];
while(cin.get(in) && (in != '\n'))
{
i++;
pOld[i]=in;
}
delete [] pNew;
pOld[i] = '\0';
return pOld;
}
Answer the question
In order to leave comments, you need to log in
With outside help and my own efforts, I decided this:
char *getline()
{
char in;
int i=0;
char* pOld = new char[1];
while(cin.get(in) && (in != '\n')){
++i;
pOld[i-1] = in;
char* pNew = new char[i+1];
for (int j=0;j<i;++j){
pNew[j] = pOld[j];
}
delete [] pOld;
pOld = pNew;
}
pOld[i] = '\0';
return pOld;
}
Буду рад комментариям и замечаниям!
That's right, segfault. You allocate an array old of size 1, and access it with an index greater than the one you allocated.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question