C programming--- how to save a string with spaces in FILE and recall them -
i saw few similar problems in website , tried follow methods either methods don't work or couldn't understand properly.
i having trouble saving strings spaces file , recalling them.
#include<stdio.h> int main() { char a[200]; char b[200]; char c[200]; char bug[100]; int s; file *fp; printf("press 1 add\npress 2 show\n"); scanf("%d",&s); if(s==1) goto level1; else goto level2; level1: gets(bug); printf("name: "); gets(a); printf("address: "); gets(b); printf("comment: "); gets(c); fp=fopen("practice2.txt", "a+"); fprintf(fp, "\n%s\t%s\t%s\t",a,b,c); fclose(fp); printf("\n1 add\n2 show\n"); scanf("%d",&s); if(s==1) goto level1; else goto level2; level2: fp=fopen("practice2.txt", "r"); if(fp==0) printf("\nempty\n"); else { while(!feof(fp)) { fscanf(fp, "\n%s\t%s\t%s\t",&a,&b,&c); printf("%s\n%s\n%s\n\n",a,b,c); } } fclose(fp); return 0; }
this code works if input strings no spaces "hello_people". if input strings spaces "hello people", doesn't show proper output. working on project in c programming , got stuck problem.
btw, in line number 17, used gets(bug). because found out if use gets() after scanf(), doesn't take first gets() input. tried using gets() after scanf() , works.
i beginner in programming. please can me fixing code make work perfectly?
additional info:
if input:
name: shane watson address: australia comment: him
then expect show result way.
#include<stdio.h> int main() { char a[200]; char b[200]; char c[200]; char line[200]; char bug[100]; int s; file *fp; printf("press 1 add\npress 2 show\n"); scanf("%d",&s); if(s==1) goto level1; else goto level2; level1: gets(bug); //scanf("% [^\n]s" , &a); printf("name:"); //fflush(stdin); scanf("% [^\n]s" , &a); fgets(a, 200, stdin); printf("address: "); scanf("% [^\n]s" , &b); fgets(b, 200, stdin); printf("comment: "); scanf("% [^\n]s" , &c); fgets(c, 200, stdin); fp=fopen("practice2.txt", "a+"); fprintf(fp, "\n %s %s %s",a,b,c); fclose(fp); printf("\n1 add\n2 show\n"); scanf("%d",&s); if(s==1) goto level1; else goto level2; level2: fp=fopen("practice2.txt", "r"); if(fp==0) printf("\nempty\n"); else { //while(!feof(fp)) while(fgets(line , sizeof(line), fp)) { //fscanf(fp, "\n %s \t %s \t %s \t",&a,&b,&c); printf("%s",line); } } fclose(fp); return 0;
}
Comments
Post a Comment