I have the following code that reads 4 numbers from user input:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMS 4
int main()
{
int nums[MAX_NUMS];
int i;
int num;
for (i = 0; i < MAX_NUMS; i++)
{
do
{
printf("Enter a value between 1 and 9: ");
scanf("%i",&num);
}
while(num > 9 || num < 1);
nums[i] = num;
}
return 0;
}
And when I run it, I get the following output:
user@USER:/cygdrive/d
$ ./test.exe
Enter a value between 1 and 9: 1
Enter a value between 1 and 9: 2
Enter a value between 1 and 9: 3
Enter a value between 1 and 9: 4
user@USER:/cygdrive/d
$
Why there is no carriage return when I press enter after entering the numbers? Am I missing something?
I am on cygwin:
user@USER:/cygdrive/d
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with: /cygdrive/i/szsz/tmpp/gcc/gcc-9.3.0-2.x86_64/src/gcc-9.3.0/configure --srcdir=/cygdrive/i/szsz/tmpp/gcc/gcc-9.3.0-2.x86_64/src/gcc-9.3.0 --prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-tune=generic --enable-languages=c,c++,fortran,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --enable-libquadmath --enable-libquadmath-support --disable-libssp --enable-libada --disable-symvers --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id --with-default-libstdcxx-abi=gcc4-compatible --enable-libstdcxx-filesystem-ts
Thread model: posix
gcc version 9.3.0 (GCC)
user@USER:/cygdrive/d
$ uname -a
CYGWIN_NT-10.0 STEPAN 3.1.5(0.340/5/3) 2020-06-01 08:59 x86_64 Cygwin
user@USER:/cygdrive/d
$ echo $TERM
xterm-256color
It seems that in your specific environment the Enter key you press to confirm you input is interpreted as a raw '\n'
. The original meaning of this character, in fact, is line feed, that means "change line without performing a carriage return" ('\r'
).
In most terminals the enter key sums the effects of \r
and \n
, and this doesn't happen in your case.
To work it around try inserting manually a '\r'
after the input insertion:
do
{
printf("Enter a value between 1 and 9: ");
scanf("%i",&num);
printf("\r");
}
while(num > 9 || num < 1);