D
D
doublench212014-10-26 20:30:49
linux
doublench21, 2014-10-26 20:30:49

Why is it displaying the rest of the line?

char str_[32];
fgets(str_, 30, stdin);
printf("%s\n", str_);

If you enter lines of smaller length, then everything seems to be fine. True, sometimes there is a request for a string several times in a row without output. I don't understand why either.
Well, the main problem is that if I mean a longer string, then it will cut it off. Displays the required amount and immediately below displays everything that is left. How to explain it??? ubuntu?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Ext4, 2014-10-26
@doublench21

printf("%s\n", str_);
I think the problem is in this place.
Try outputting like this:
And here's how fgets() works:

The fgets() function reads at most num-1 characters from the input stream and places them in the character array pointed to by str. Characters are read until a newline or EOF is read, or until the specified limit is reached. At the end of reading characters, a null character is placed immediately after the last character. The newline character is preserved and becomes part of the array addressed by the str element.

N
neolink, 2014-10-26
@neolink

char str_[32] = {0};

J
jcmvbkbc, 2014-10-26
@jcmvbkbc

How to explain it

It looks like your code is running in a loop. You type a line and press enter -- fgets reads the first 30 characters, leaving the rest in the input buffer -- printf prints them out, the loop starts again, fgets reads the next 30 characters -- whatever was left in the buffer from the previous read. If you want to flush the buffer use fflush(stdin).

I
Ivan Ershov, 2014-10-28
@iwanerhov

void PrintStr(const char *str)
{
   int size = strlen(str);
   for(int i = 0; i < size; ++i)
      std::cout << str[i];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question