Hello there, I am having trouble copying text into a string, what am i doing wrong?

#include <stdio.h>

int main() {
	char instructions[80];
	
	FILE *f;
	f=fopen("a3.txt","r");
	
	while (fscanf(f,"%s",instructions != EOF){
		fscanf(f,"%s",instructions);
	}
	
	printf("%s",instructions);

	
	
}

the contents of a3.txt are
B404
239A
2412
5345
350C
C000.

Dani AI

Generated

: was right about the syntax error and the double read, but there are a few more robustness points worth adding.

  • Always check fopen for NULL and call fclose when done.
  • Do not rely on comparing fscanf to EOF; fscanf returns the number of conversions performed (or EOF on input failure before any conversion). Test for the expected count (e.g. == 1 for one %s).
  • Prevent buffer overflow by giving a width in the format (e.g. %79s for an 80-byte buffer).
  • If you need whole lines (including spaces) use fgets instead of %s, which splits on whitespace.

Example (safe token read, different from the examples already posted):

#include <stdio.h>

int main(void) {
    char instructions[80];
    FILE *f = fopen("a3.txt", "r");
    if (!f) { perror("fopen"); return 1; }

    while (fscanf(f, "%79s", instructions) == 1) {
        puts(instructions);
    }

    fclose(f);
    return 0;
}

If the file contains full lines or you want to preserve spaces, use fgets and strip the trailing newline:

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

char line[80];
while (fgets(line, sizeof line, f)) {
    size_t len = strlen(line);
    if (len && line[len-1] == '\n') line[len-1] = '\0';
    puts(line);
}

asked about a 2D string: for a fixed maximum use char lines[MAX_LINES][MAX_LEN] and read into lines[i++] with bounds checks. For an unknown number of lines allocate an array of char* and realloc as you read, using strdup (or malloc+strcpy) for each line.

Recommended Answers

All 3 Replies

Hello there, I am having trouble copying text into a string, what am i doing wrong?

#include <stdio.h>

int main() {
	char instructions[80];
	
	FILE *f;
	f=fopen("a3.txt","r");
	
	while (fscanf(f,"%s",instructions != EOF){
		fscanf(f,"%s",instructions);
	}
	
	printf("%s",instructions);

	
	
}

the contents of a3.txt are
B404
239A
2412
5345
350C
C000.

There are two things wrong with your code. In the 'while (fscanf(f,"%s",instructions != EOF)' line you have a missing "close paren". It should be 'while (fscanf(f,"%s",instructions) != EOF)'. The next problem is that you are reading your file twice. Once in the while statement and once in the body of the while statement. I would do the following

while (fscanf(f,"%s",instructions) != EOF){
printf("%s",instructions);
}

commented: good explanation +13

How It can be If we want to get from text to 2D string.

Regards,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.