C ++ read buffer

I am trying to read a buffer in C ++ one character at a time before '\ n' and initialize a char array with these characters using a do-while loop. I know I can use cin.getline (), but I want to try this 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;
} 

This gives me the wrong result - the correct text falls into a couple of lines of square brackets mixed with other strange characters.

+3
source share
6 answers

First, after all the text, you should add '\0'at the end of the line

it should look like buffer[ index ] = 0;because you have to rewrite your character \nthat you added too.

Of course, there are other things you should check, but they are not your main concern.

  • , - 1023 +
  • cin.eof()
+5

.

char buffer[1024] = "";

, buffer 0. , , 0,

buffer[index] = 0;

.

, ( ), 1024 , - .

+3

:

  • 1024, .
  • , char.

. , , , , char .

#define MAX 1024

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

 do 
 {
  // buffer full.
  if(index == MAX-1)
   break;

  cin.get( temp );
  buffer [ index ] = temp;
  index ++;

 }
 while ( temp != '\n' );

 // add null char at the end.
 buffer[index] = '\0';

 cout << buffer << endl;

 return 0;
} 
+2

, :

(1) . 8, 16 32- . , ASCII?

(2) "\n", "\ r\n" "\ r" "\n" . , \r ?

+1

, , . , : char buffer[1024] = {0}; .

0

You do not put '\ 0' at the end of the line. In addition, you should really check for buffer overflow conditions. Stop reading when the index reaches 1024.

0
source

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


All Articles