I want to have a loop of scanf that repeats until the user presses enter.
#include <stdio.h>
int main() {
char num[127];
int i=-1;
do
{
i ;
scanf("%c ", &num[i]);
}while ((num[i]!='\n') && i<=127);
printf("%c", num[3]);
return 0;
}
With this code, when I input > 0 1 2 3 4 5 6 , the output num[3] is nothing. How can I fix this? I already tried using while and for, but i get the same problem.
CodePudding user response:
What you need is something like the following
#include <stdio.h>
#include <ctype.h>
int main(void)
{
enum { N = 127 };
char num[N];
size_t len = 0;
char c;
while ( len < N && scanf( "%c", &c ) == 1 && c != '\n' )
{
if ( !isblank( ( unsigned char )c ) ) num[len ] = c;
}
if ( 3 < len ) printf( "%c\n", num[3] );
return 0;
}
The if statement
if ( !isblank( ( unsigned char )c ) ) num[len ] = c;
may be substituted for this one if you are going to enter only digits
if ( isdigit( ( unsigned char )c ) ) num[len ] = c;
If to use getchar
then the program will look like
#include <stdio.h>
#include <ctype.h>
int main(void)
{
enum { N = 127 };
char num[N];
size_t len = 0;
int c;
while ( len < N && ( c = getchar() ) != EOF && c != '\n' )
{
if ( isdigit( c ) ) num[len ] = c;
}
if ( 3 < len ) printf( "%c\n", num[3] );
return 0;
}
CodePudding user response:
Using the format specifier "%c "
, scanf
will never write \n
into buf[i]
except for i == 0
. (If the first character of input is a newline, it will be written to buf[0]
. Otherwise, all newlines will be discarded because of the whitespace in the conversion specifier.) If you are entering data interactively, the program will not terminate correctly, since eventually the scanf
will invoke undefined behavior when it tries to write to buf[127]
Also, you're not checking the value returned by scanf. It's not clear to me what you want to do with whitespace, but perhaps you want something like:
#include <stdio.h>
int
main(void)
{
char num[127];
int i=-1;
while( i < 125 && scanf("%c", &num[ i]) == 1 && num[i] != '\n' ){
; /* scanf is the wrong tool for this!! */
}
printf("%c", num[3]);
return 0;
}
(But note that using scanf
is absolutely the wrong way to read a single character. fgetc
, getc
, and getchar
are better for that.)