I received data to stream using scanf()
and sent it to client.txt
using fprintf():
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("clear");
int servicestart;
char tmp1[100], tmp2[100], tmp3[100], tmp4[100], tmp5[100];
puts(">>Library Service<<\n1.Register 2.Log in 3.Exit Program");
scanf("%d", &servicestart);
switch (servicestart)
{
case 1:
{
system("clear");
FILE* fp1 = fopen("client.txt", "w");
if (fp1 == NULL)
{
puts("Write Error!!");
return 0;
}
puts("You selected Register");
puts("Enter Student ID | Password | Name | Address | Phonenumber");
puts("ex)2018|ssu|DanielHong|Gaepo-dong|01031414473");
printf("\n\n");
scanf("%s|%s|%s|%s|%s", tmp1, tmp2, tmp3, tmp4, tmp5);
fprintf(fp1, "%s %s %s %s %s", tmp1, tmp2, tmp3, tmp4, tmp5);
fclose(fp1);
}
return 0;
}
However, when I entered 2018|asdf1234|danielhong|gaepo-dong|01023232323
there was 2018|asdf1234|danielhong|gaepo-dong|01023232323 p \ ����
in client.txt
.
I didn't enter p \ ����
clearly.
I was in agony about it but don't having any clue about solution.
Can somebody help me for this problem?
The format specifier "%s"
reads until the next whitespace. The next whitespace in your input is the newline ('\n'
) at the end of the line. Use
scanf("%99[^|]|%99[^|]|%99[^|]|%99[^|]|%99s", tmp1, tmp2, tmp3, tmp4, tmp5);
Instead. %[]
is a scanset that matches all characters in the brackets. If the characters are prepended with a ^
they are excluded.
Please, never use "%s"
or a scanset without specifying a width for the conversion specifier to limit the characters maximal read. Since your arrays are 100 chars long specify 99 so there is space left for the terminating '\0'
character.
You should also check, if scanf was successful before proceeding to process the input. scanf()
returns the number of conversions successfully performed. So in your case you schould compare the return value with 5:
if (scanf("%99[^|]|%99[^|]|%99[^|]|%99[^|]|%99s", tmp1, tmp2, tmp3, tmp4, tmp5) != 5) {
; // handle error
}