'The number of inputs I have to enter is one more than required for the output to display [duplicate]
I have to enter one more input than required for the code to start running. For example, for 2 strings I have to enter 3 strings, only then the output shows. Please help.
#include<stdio.h>
#include<string.h>
int main () {
int num_strings;
char arr[num_strings][100];
scanf("%d",&num_strings);
for (int i=0;i<=num_strings-1;i++) {
scanf("%s\n",&arr[i]);
}
for (int j=0;j<=num_strings-1;j++) {
if (strlen(arr[j])>10) {
printf("%c%d%c",arr[j][0],strlen(arr[j])-2,arr[j][strlen(arr[j])-1]);
printf("\n");
} else {
printf("%s",arr[j]);
printf("\n");
}
}
}
Solution 1:[1]
The following
int num_strings;
char arr[num_strings][100];
scanf("%d",&num_strings);
is out of order. Changing the value of num_strings does not retroactively adjust the size of arrays that were initialized using this variable. As such, arr is initialized with an indeterminate value, since num_strings is uninitialized. This is an example of invoking Undefined Behavior.
&arr[i] is of type char (*)[100], you simply want arr[i], which will decay to a char * (the correct type for %s) when passed to scanf.
Remove the trailing whitespace from the scanf format, or it will hang until it reads non-whitespace ("%s\n" -> "%s").
Limit the length of the strings you read with a field-width specifier as to not overflow the buffers (%99s).
strlen returns a size_t, the format specifier for printing this is %zu.
Note that scanf can fail for a variety of reasons. Consider checking that the return value of each call was (or was not) the expected number of conversions, e.g.,
if (2 != scanf("%d%d", &a, &b))
/* failure */;
and handle any failures.
Here is a functional version of your program, without error checking:
#include <stdio.h>
#include <string.h>
int main(void) {
int num_strings;
scanf("%d", &num_strings);
char arr[num_strings][100];
for (int i = 0; i < num_strings; i++)
scanf("%99s", arr[i]);
for (int j = 0; j < num_strings; j++) {
if (strlen(arr[j]) > 10) {
printf("%c%zu%c\n",
arr[j][0], strlen(arr[j]) - 2,
arr[j][strlen(arr[j]) - 1]);
} else {
printf("%s\n", arr[j]);
}
}
}
stdin:
3
hello
thisisalongerstring
world
stdout:
hello
t17g
world
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
