Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading buffer C++

Tags:

c++

I'm trying to read buffer in C++ one character at the time until '\n', and initialize char array with these characters using do-while loop. I know I could use cin.getline(), but I want to try it on my own.

int main()
{
    char buffer [1024];
    int index = 0;
    char temp;

    do 
    {
        cin.get( temp );
        buffer [ index ] = temp;
        index ++;
    }
    while ( temp != '\n' );

    cout << buffer << endl;

    return 0;
} 

It gives me incorrect result-the proper text fallow by couple of lines of squre brackets mixed with other weird symbols.

like image 918
Kary Avatar asked Jul 01 '26 05:07

Kary


1 Answers

At first, after whole text you have to append '\0' as end of string

it should look like buffer[ index ] = 0; because you should rewrite your \n character which you append too.

Of course, there are other things which you should check but they are not your main problem

  • length of your input because you have limited buffer - max length is 1023 + null byte
  • end of standard input cin.eof()
like image 150
Gaim Avatar answered Jul 04 '26 05:07

Gaim