0

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);
2
  • &sentence[1000] is a pointer to one element beyond the end of the array. Commented Jan 6, 2018 at 16:22
  • Also, scanf("%s", ...) will read only one word. You can read entire lines (up to and including the terminating new-line character) with fgets(). Commented Jan 6, 2018 at 16:23

1 Answer 1

1
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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.