For my practice assignment I have to use either gets() or fgets(). I chose fgets() as its more secure.
The first input is meant to be able to hold a maximum of 5 characters. So i gave the char array a size of 6 to accommodate the trailing '\0'.
I found the fgets() issue of it adding a trailing '\n' when you press Enter (using stdin with fgets())
I done a bit of research and found a for loop to try and get rid of it. However, it doesnt seem to be working and i cant for the life of me figure out why.
Its still skipping the next input when i type in 5 characters.
Here is the code:
#include <stdio.h> #include <string.h> int main(void) { //Declare char arrays char arcInputString5[6]; char arcInputString10[11]; char arcInputString15[16]; char arcInputString20[21]; int clean1, clean2, clean3, clean4; // int nStrLen1, nStrLen2, nStrLen3, nStrLen4; // nStrLen1 = nStrLen2 = nStrLen3 = nStrLen4 = 0; printf("\nPlease Input String 1 - Max Length 5: "); //gets(arcInputString5); fgets(arcInputString5, 6, stdin); for(clean1 = 0; clean1 < strlen(arcInputString5); clean1++) { if(arcInputString5[clean1] == '\n' || arcInputString5[clean1] == '\r') { arcInputString5[clean1] = '\0'; break; } } printf("\nPlease Input String 2 - Max Length 10: "); //gets(arcInputString10); fgets(arcInputString10, 10, stdin); printf("\nPlease Input String 3 - Max Length 15: "); //gets(arcInputString15); fgets(arcInputString15, 15, stdin); printf("\nPlease Input String 4 - Max Length 20: "); //gets(arcInputString20); fgets(arcInputString20, 20, stdin); printf("\nThankyou For Your Inputs - They Are Shown Back To You Below\n"); puts(arcInputString5); puts(arcInputString10); puts(arcInputString15); puts(arcInputString20); printf("\nThe String Lengths For Each Input Are Listed Below"); printf("\n%d", strlen(arcInputString5)); printf("\n%d", strlen(arcInputString10)); printf("\n%d", strlen(arcInputString15)); printf("\n%d", strlen(arcInputString20));
}
Ive tried multiple ways of doing the for loop such as using the number 6 instead of "strlen(arcInputString5)"
Any help would be appreciated.
EDIT:
EXAMPLE INPUT:
asd d
EXAMPLE OUTPUT:
Please Input String 2 - Max Length 10: //skips this Please Input String 3 - Max Length 15: //this is the next line for input