I was trying to input a string of characters and only output the last and the first character respectively. Below is the code I'm using.
#include<stdio.h>
int main(){
for(int i=0;i<3;i ){
int n; // length of the string
char string[101];
scanf("%d %s", &n, &string);
fflush(stdin); // sometimes I also use getchar();
printf("%c%c", string[n 1], string[0]);
}
printf("\n");
return 0;
}
I'm using for loop because i wanted to input the string 3 times, but when I ran the code the input isn't what I expected. If I input e.g.
5 abcde
output
a //there's space before the a
can you help me tell where I've gone wrong?
input:
5 abcde
6 qwerty
3 ijk
excpeted output:
ea
yq
ki
CodePudding user response:
Few problems in your code:
In this statement
scanf("%d %s", &n, &string);
you don't need to give &
operator with string
. An array name, when used in an expression, converts to pointer to first element (there are few exceptions to this rule). Also, the size of string
array is 101
characters but if you provide input more than 101
characters, the scanf()
end up accessing string
array beyond its size. You should restrict the scanf()
to not to read more than 100
characters in string
array when input size is more than that. (keep the remain one character space is for null terminating character that scanf()
adds). For this, you can provide width modifier in the format specifier - 0s
.
You are not validating the string length input against the input string from user. What happen, if the input string length is greater than or less than the actual length of input string!
fflush(stdin)
is undefined behaviour because, as per standard, fflush
can only be used with output streams.
I was trying to input a string of characters and only output the last and the first character respectively.
For this, you don't need to take the length of the string as input from user. Use standard library function - strlen()
. This will also prevent your program from the problems that can occur due to erroneous length input from user, if that is not validated properly.
Putting these altogether, you can do:
#include <stdio.h>
#include <string.h>
int main (void) {
for (int i = 0; i < 3 ; i ) {
char string[101];
printf ("Enter string:\n");
scanf("0s", string);
printf("Last character: %c, First character: %c\n", string[strlen(string) - 1], string[0]);
int c;
/*discard the extra characters, if any*/
/*For e.g. if user input is very long this will discard the input beyond 100 characters */
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
}
return 0;
}
Note that, scanf(%<width>s, ......)
reads up to width
or until the first whitespace character, whichever appears first. If you want to include the spaces in input, you can use the appropriate conversion specifier in scanf()
or a better alternative is to use fgets() for input from user.
CodePudding user response:
Line 11: string[n 1] -> string[n-1]