Reputation: 33
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.
Upvotes: 3
Views: 15998
Reputation: 455020
Two things:
You can trying doing it the following way. This way if you find a fine exceeding the buffer size, we truncate it and also add the null char at the end ouside the loop.
#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;
}
Upvotes: 3
Reputation: 6844
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
cin.eof()
Upvotes: 6
Reputation: 2243
You are not putting a '\0' at the end of the string. Additionally, you should really check for buffer overflow conditions. Stop reading when index gets to 1024.
Upvotes: 0
Reputation: 65599
Several issues I noted:
(1) What character encoding is the input. You could be reading 8,16, or 32 bit characters. Are you sure you're reading ASCII?
(2) You are searching for '\n' the end of line character could be '\r\n' or '\r' or '\n' depending on your platform. Perhaps the \r character by itself is your square bracket?
Upvotes: 1
Reputation: 25523
You stop filling the buffer when you get to a newline, so the rest is uninitialised. You can zero-initialise your buffer by defining it with: char buffer[1024] = {0};
This will fix your problem.
Upvotes: 0
Reputation: 2473
You're not null-delimiting your buffer.
Try to change the first line to
char buffer[1024] = "";
This will set all characters in buffer
to 0. Or, alternatively, set only the last character to 0, by doing
buffer[index] = 0;
after the loop.
Also, (as correctly pointed by others) if the text is longer than 1024 characters, you'll have a buffer overrun error - one of the most often exploited causes for security issues in software.
Upvotes: 3