1

I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason

int main()
{
    FILE *stream;

    stream = fopen("file.txt", "w");

    char str[] = { '\0 ' };
    scanf("%s", &str);
    fprintf(stream, "%s.\n", str);


    fclose(stream);

    return(0);
}
4
  • How long is str? Commented Apr 12, 2017 at 21:06
  • How much does scanf("%s".. read? Commented Apr 12, 2017 at 21:07
  • 20 characters at most Commented Apr 12, 2017 at 21:11
  • 2
    Is str long enough? Does scanf prevent more than 20 characters to be read Commented Apr 12, 2017 at 21:12

2 Answers 2

3

try this, should work just fine. It did for me so it should for you too.

#include <stdio.h>
#include <string.h>

int main()
{
FILE *stream;

stream = fopen("ceva.txt", "w");
if (stream == NULL) {
   perror("Failed: ");
   return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);


fclose(stream);

return 0;}
Sign up to request clarification or add additional context in comments.

5 Comments

Change scanf("%s", str); to scanf("%249s", str);
Yes, thank you, guys. I just did it to present a code that works for the purpose of printing into a file something read from the keyboard. I just rushed in and forgot. Thanks again
Perhaps also check stream is not null as well
Robust code always checks the return value of input functions. if (scanf("%249s", str) == 1) fprintf(stream, "%s.\n", str);
In most cases scanf("%s",...) is not what most users want to use since scanf("%s") just reads words terminated by whitespace, which is quite confusing in many situations, e.g. pressing ENTER does not make it return since ENTER is whitespace. In many cases you are better off with using fgets().
0

You must change scanf with fscanf

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.