Good afternoon. How can I write the function nonOpGetLine:
Code:
#include <stdio.h>
#ifndef MAXLINE
#define MAXLINE 100
#endif
int nonOpGetLine(char* s, int lim);
int nonOpGetLine(char* s, int lim)
{
int c;
int i = 0;
while(i < lim - 1)
{
c = getchar();
if(c == EOF)
break;
if(c == '\n')
break;
s[i++] = c;
}
s[i] = '\0';
return i;
}
int main()
{
int n;
char s[MAXLINE];
while( (n = nonOpGetLine(s, MAXLINE)) > 0)
fputs(s, stdout);
putchar('\n');
return 0;
}
with streams like fgetc(stdin)? I tried to replace every getchar() with it but it didn't work how I was expecting.
Code:
#include <stdio.h>
#ifndef MAXLINE
#define MAXLINE 100
#endif
int nonOpGetLine(char* s, int lim);
int nonOpGetLine(char* s, int lim)
{
int i = 0;
while(i < lim - 1)
{
fgetc(stdin);
if(fgetc(stdin) == EOF)
break;
if(fgetc(stdin) == '\n')
break;
s[i++] = fgetc(stdin);
}
s[i] = '\0';
return i;
}
int main()
{
int n;
char s[MAXLINE];
while( (n = nonOpGetLine(s, MAXLINE)) > 0)
fputs(s, stdout);
putchar('\n');
return 0;
}
input:
thames
output:
m