Nhập file.txt trong C bị lặp dòng cuối

Cho một file .txt như thế này:

apple qua_tao
banana qua_chuoi
hello xin_chao

Nhập file dữ liệu vào C:

    char s1[100],s2[100];
      FILE *f = fopen("tudien.txt","r");
      if(f == NULL){
        perror("Failure when opening\n");
        return ;
      }
      while(!feof(f)){
          fscanf(f,"%s %s",s1,s2);
          printf("%s %s\n",s1,s2);
      }
      fclose(f);

input:

apple qua_tao
banana qua_chuoi
hello xin_chao
hello xin_chao

mn cho mình hỏi có cách nào để sửa không ạ

Có 1 kí tự xuống dòng (hoặc kí tự phân cách) nằm ở cuối tập tin đầu vào.
Cách 1: Xóa kí tự ở cuối đi.
Cách 2: Ổn hơn.
Bạn chuyển fscanf() vào chung với feof ở chỗ while thế này:

while(!feof(f) && fscanf(f, "%s %s", s1, s2) == 2){

Vì sao lại so sánh với 2? Hãy đọc tài liệu về hàm fscanf() (tương tự scanf()):
https://www.cplusplus.com/reference/cstdio/fscanf/
Đọc kĩ phần Return nhé.

2 Likes

theo mình hiểu và search được thì là ntn,

NAME
       scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf 

       ...

RETURN VALUE
       These functions return the number of input items  successfully  
matched and assigned, which can be fewer than provided for, or even zero 
in the event of an early matching failure.

       The value EOF is returned if the end of input is reached before  
either the  first  successful conversion or a matching failure occurs. 
 EOF is also returned if a read error occurs, in which case the error 
indicator for  the  stream  (see ferror(3)) is set, and errno is set indicate 
the error.

link:

và một số ví dụ về scanf:

thì

fscanf(f,"%s %s",s1,s2) 

luôn ra bằng 2 chứ nhỉ :v
Mình vẫn không hiểu lắm, bạn giải thích thêm được không

Không gì bằng ví dụ thực tế:

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?