The Daele
The Daele

Reputation: 15

Appending user input array to file [c]

I'm trying to add a sentence to a text file but I seem to only add one word of the sentence instead of the whole sentence. I know that using fputs("this is a sentence", pFileText); It works just fine with adding text, but not by adding a string variable. What am I doing wrong?

char sentence[1000];

FILE * pFileText;

pFileText = fopen("text.txt", "a");

printf("Enter text: ");
scanf("%s", &sentence[1000]);

fputs("\n", pFileText);
fputs(sentence, pFileText);
fclose(pFileText);

Upvotes: 0

Views: 675

Answers (1)

user2736738
user2736738

Reputation: 30926

scanf("%s", &sentence[1000]);

will be

scanf("%s", sentence);

Enable compiler warnings and run the same code. It will tell you where you went wrong.

gcc -Wall -Werror progname.c

The second example is passing an char* but first one is attempting to pass an char(*)[1000]. scanf's %s format specifier expects a char* not char(*)[1000].

fegts is the correct alternative here I would say, and much cleaner to use.

fgets(sentence,1000,stdin);

with a check of return value of fgets would do the job you want to achieve here. (You wanted to read a line and fgets does that).

Upvotes: 1

Related Questions