Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

readline char array limit in C


ghost's Avatar
0 0

#include <stdio.h>

int main (void)

{ int i; char line[81]; void readLine (char buffer[]);

for ( i = 0; i &lt; 3; ++i )
{
    readLine (line);
    printf (&quot;%s&#92;n&#92;n&quot;, line);
    }
    
    return 0;

}

void readLine (char buffer[] ) { char character; int i = 0;

          do 
          {
              
              character = getchar ();
              buffer[i] = character;
              ++i;
                              
            }
          while ( character != &#39;&#92;n&#39; );
          
          buffer[i-1] = &#39;&#92;0&#39;; 
           
          }

The problem is I want to set a limit on the array so if more than 81 characters are put in with no new line character, it will store the null character at buffer[80] and then display the 80 characters. I've tried several things, but I really need to go to dinner right now so if you want I can fill you guys in later with more detail. Thanks in advance for any help.

edit- Sorry I noticed a couple syntax errors from when I was copying the code down into this thread. Like I said I was in a hurry, but it's fixed now.


ghost's Avatar
0 0
#include &lt;stdio.h&gt;

int main (void)

{
    int i;
    char line[81];
    void readLine (char buffer[]);
    
    for ( i = 0; i &lt; 3; ++i )
    {
        readLine (line);
        printf (&quot;%s&#92;n&#92;n&quot;, line);
        }
        
        return 0;
}

void readLine (char buffer[], )
     {
              char character;
              int i = 0;
              
              do 
              {
                  
                  character = getchar ();
                 if(i&lt;=80)
                 { 
                         buffer[i] = character;
                          ++i;
                 }
                                  
                }
              while ( character != &#39;&#92;n&#39; );
              
              {buffer[i-1] = &#39;&#92;0&#39;; 
               
              }

How is that?


ghost's Avatar
0 0

Try this out, I didn't test it but the idea makes sense.

{
     
char character;
int i = 0;

do
{
character = getchar();
buffer[i++] = character;
}
while ( character != &#39;&#92;n&#39;);

if ( i &gt; 80 ) buffer[80] = &#39;&#92;0&#39;;

}```

ok changed it a little

Edit 2 : you might try strncpy also

ghost's Avatar
0 0

Yes, thank you. The difference was I needed to put the if (i<=81) statement after character = getchar (). I was putting the if (i<=81) before that, which was causing some unwanted results.