My objective is to print out the first N characters (the len variable) of a string using a simple for loop. However, the code doesn't seem to work. eg with the input printFrstChars("Example",3)
the code should print out Exa
, but it does not print out anything .
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void printFrstChars (char inp[], int len)
{
for(int i = 0; inp[i] != '\0' && i <= len; i++){
printf("%s", inp[i]);
}
}
int main ()
{
int len = 0;
char inp[100];
printf("Input string and length:\n");
scanf("%99s %d", &inp, &len);
printFrstChars(inp, len);
return 0;
}
I went over the code multiple times and I (obviously) did not find the mistake that causes this. I would guess that it is either a mistake subtle enough to hide from my beginner eye, or the whole approach is wrong.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void printFrstChars (char inp[], int len)
{
for(int i = 0; inp[i] != '\0' && i < len; i++){
printf("%c", inp[i]);
}
printf("\n");
}
int main ()
{
int len = 0;
char inp[100];
printf("Input string:\n");
scanf("%99s", inp);
printf("Input length (99 or less):\n");
scanf("%d", &len);
printFrstChars(inp, len);
return 0;
}
Separating inputs, scanning into inp
instead of &inp
, printing each char with %c
format, and iterating while i < len
instead (printing a new line after). My 2 cents.
Thanks to @AndrewHenle for pointing out the overflow. The %99s
format specifier only reads max 99 chars (and the prompt states that too).
I think you need to remove the '99' from %99s where you are taking the string as an input. Just %s will work in the case, you are not entering a string with 'spaces'. Also, In case you want to print the N number of characters, you need to put len<N or len<=N-1. Just, put inp instead of &inp.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.