How to read data(mainly string) from keyboard and write it in a .txt file? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to read data(mainly string) from keyboard and write it in a .txt file?

This is my code #include<stdio.h> int main() { char a[100]; FILE * fptr; fptr = fopen("sujan.txt", "w"); if (fptr == NULL) { printf("Error while opening file...."); exit(1); } printf("Please Enter your text:\n"); scanf("%s", &a[100]); fprintf(fptr, "%s", a[100]); fclose(fptr); return 0; }

25th May 2020, 7:46 AM
Sujan Kharal
Sujan Kharal - avatar
1 Answer
0
When dealing with strings (and more in general arrays) the name is already a pointer to the first element. So you have to pass to scanf and fprintf only the name of the string, %s needs the addres of the first element of the string to use it. Passing &a[100] you are passing the address of the 100th element.
25th May 2020, 8:36 AM
Alessandro Palazzolo
Alessandro Palazzolo - avatar