Reputation: 188
I want to read exactly 4 chars from the console for this I'm doing this, but it is not working as I expect it to, it reads more & less chars ..
int main()
{
char arr[4];
scanf("%s",&arr);
printf("%s",arr);
return 0;
}
My Input to this program is this:
sachinjainsachin
sachinjainsachin
It prints the whole the char array while the size of array is 4
. I don't know why it is printing more than the size, it should to print only 4 chars i.e. sachi
Upvotes: 2
Views: 6754
Reputation: 7352
What you are doing is undefined behavior. The fact that it works at all is merely coincidental. What happens in this case is random and irrelevant, as its undefined. writing outside the bounds of your string array with scanf()
will at best cause what you saw. At worst it will crash your program with a segmentation fault.
Take note that arr[4] is only good for a string with 3 characters and a terminator. Every string in C needs a \0
as terminator at the end of it.
If you don't need a variable max length, you can do:
int main (void)
{
char str[5] = { };
scanf("%4s", str);
printf("%s",str);
return 0;
}
Additionally, if you want to read a variable amount of characters into your string, you can do it like this:
int main (void)
{
char del[128] = { };
char str[5] = { };
int max = 4;
sprintf(del, "%%%dc", max);
scanf(del, str);
printf("%s",str);
return 0;
}
Upvotes: 6
Reputation: 1973
What if you need all input characters, including new lines? The function does the job:
void fetchNextNchars(char arr[], int n) {
char c;
int i = 0;
for (; i < n; i++) {
c = getchar();
if (c != EOF) {
arr[i] = c;
}
else
break;
}
arr[i] = '\0';
}
The array arr must be at least n + 1 characters long to hold last '\0'.
Upvotes: 0
Reputation: 12668
you can use fgets() to scan a variable number of chars. Just do
char buffer[100];
fgets(buffer, 4, stdin);
and you will read only four characters, followed by a \n
(case the line has less of three characters and one \0
at the end signalling the end of string.
the space allocated for the buffer is normally the amount passed as the second parameter, but no need to do that. Normally, fscanf(3)
is called
to fill one complete line of input this way:
char line[1024];
while (fgets(line, sizeof line, stdin) != NULL) { /* bla, bla, bla... */
but there's no need to proceed this way. You can use it to scan for only four chars with fscan(buffer, 4, stdin);
Take into account that fgets(3)
finishes input when it encounters an end of line (\n
char, scanf(3)
skips spaces and doesn't include trailing blanks also) if it happens to be before reaching the number you pass. If you want to read exactly that number of chars, you'll have to use fread(3)
or read(2)
instead.
Upvotes: 0
Reputation: 108938
The best way is using getchar()
void quit(const char *msg) {
fprintf(stderr, "Program aborted");
if (msg) fprintf(stderr, ": %s", msg);
fprintf(stderr, ".\n");
}
// ...
int ch;
ch = getchar(); if (ch == EOF) quit("error"); arr[0] = ch;
ch = getchar(); if (ch == EOF) quit("error"); arr[1] = ch;
ch = getchar(); if (ch == EOF) quit("error"); arr[2] = ch;
ch = getchar(); if (ch == EOF) quit("error"); arr[3] = ch;
// ...
Upvotes: -1
Reputation: 121397
Since you want to read 4 chars (but as a string), you need the changes:
1) your array size needs to be at least 5.
2) You are passing the address of an array which is of type char(*)[]
whereas scanf()
expects char*
for format specifier %s
.
To read only 4 chars, you can specify the length in the format string. So it should be
char arr[5];
scanf("%4s",arr);
Personally I would use fgets()
over scanf()
:
fgets(arr, sizeof arr, stdin);
and manipulate it later using sscanf()
(such as removing the trailing newline, if present; reading one X number of characters from it etc).
fgets()
+ sscanf()
is better as it doesn't have the typical problems associated with scanf(), such as:
1) buffer overflow
2) Not clearing the input buffer etc
See: Why does everyone say not to use scanf? What should I use instead?
Upvotes: 1
Reputation: 4454
Strings in c language must be null terminated.if you want to write 4 characters,then '\0'
must be the 5th element in the array.use it like this:
int main()
{
char arr[5];
scanf(" %4s",arr);
printf("%s\n",arr);
return 0;
}
Upvotes: 2
Reputation: 4232
printf("%s",arr);
This prints a null terminated array. So it prints characters until it reaches '\0' character. If arr[3] != '\0'
it will print more than you intended.
If you want to just print 4 characters it is probably better to print them seperately.
for (int i = 0; i < 4; ++i)
{
printf("%c", arr[i]);
}
Upvotes: 0