R
R
ReD2020-06-29 23:30:46
C++ / C#
ReD, 2020-06-29 23:30:46

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; 
}

But this causes a segmentation fault.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
ReD, 2020-06-30
@trinitr0

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; 
}

Буду рад комментариям и замечаниям!

A
Alexander Ananiev, 2020-06-30
@SaNNy32

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 question

Ask a Question

731 491 924 answers to any question