제발 도와주세요ㅜㅜ replit에서 결과가 이상하게 떠요..

챙의 이미지

전체적인 함수를 만들었는데...
메인과 함수1만 잘라서 업로드합니다.. fscanf가 읽히지 않아서

aa 10 20 30 40
bb 23 24 45 65

이라는 내용이 쓰인 input2.txt가 있다고 치면

exe창에서 1 입력하고, input2.txt입력해도 fscanf가 제대로 작동하지 않아 p[0].name에 모든 내용물이 들어가버리게 됩ㄴ다... 뭐가 문제일까요ㅜㅜ

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
 
void func0(void);//1,2,3선택 및 이동 함수
void func1(char fname[30]); //1번 함수
void func2(void);//2번 함수
void func3(void);//3번 함수
 
 
int num = 0, num2 = 0, c = 0;
char fname[30];
struct aa {
    char name[30];
    int age;
    int math, english, history;
}info, * p = NULL;
int i = 0, k;
int j;
 
 
 
int main() {
    func0();
    free(p);
}
 
void func0(void) {
    do {
        printf("============================\n");
 
        printf("1) Insert\n2) Sort\n3) Quit\n");
        printf("Select a menu : ");
        scanf(" %d%*c", &num);
 
 
        if (num == 1) {
            if (c == 0) {
                printf("File name : ");
                gets(fname);
                printf("\n");
                func1(fname);
            }
            else {
                printf("Insert can be executed only one time.");
                printf("\n============================");
                exit(1);
            }
        }
        else if (num == 2) {
            func2();
        }
        else if (num == 3) {
            func3();
        }
        else {
            printf("There is no menu. Program terminates.");
            printf("\n============================");
            exit(1);
        }
    } while (num == 1 || num == 2);
}
 
void func1(char fname[30]) {
    c = 1;
    FILE* fp;
    fp = fopen(fname, "rt");
 
 
 
    int ch;
    int count = 1;
    while ((ch = fgetc(fp)) != EOF) {
        if (ch == '\n')
            count++;
    }
    j = count;
    fclose(fp);
 
 
    freopen(fname, "rt", fp);
    p = malloc(sizeof(struct aa) * j);
 
 
    while (fscanf(fp, "%s %d %d %d %d", p[i].name, &p[i].age, &p[i].math, &p[i].english, &p[i].history) != EOF) {
 
        i++;
    }
 
 
 
    printf("No  Name  Age  Math   English  History\n");
    for (i = 0; i < j; i++) {
        printf("%d %s %d %d %d %d\n", i + 1, p[i].name, p[i].age, p[i].math, p[i].english, p[i].history);
    }
 
 
    fclose(fp);
}
세벌의 이미지

printf 함수를 중간중간에 넣어보셔요. 어디에서 기대한 값이 안 나오는지.
좀 더 고차원적으로 하려면 debug 에 대해 공부해 보셔요.

챙의 이미지

replit에서는 공백을 못 읽어들이는 건가요..?
공백을 기준으로 메모장의 덩어리들을 쪼개어 구조체배열에 할당하는 fscanf가 정상작동하지 않고, 메모장의 모든 내용들이 구조체배열 맨 첫째공간에 다 들어가버려요..

세벌의 이미지

scanf 는 공백을 구분자로 쓸 겁니다. gets() (파일을 다룬다면 fgets() 등) 다른 함수를 고려해야 할 듯.

익명 사용자의 이미지

이 문제는 scanf와는 관련이 없습니다.
복사붙여넣기로 그대로 문제가 재현되도록 코드를 올리면 더 친절한 답을 얻을 수 있습니다.
문제와 상관없다고 생각되는 부분을 삭제하면서 코드를 수정하다보면 정확한 문제가 어디였는지를 찾을 수 있습니다.
코드에 다른 문제도 많이 있지만, freopen 직전의 fclose만 삭제하면 일단은 원하는 결과를 얻을 수 있을지도.

@세벌 도움을 주고자하는 욕구가 넘침은 알겠으나, 잘못된 도움은 피해가 될 수도 있음을 아시길.

챙의 이미지

몇날몇일을 고민하여 만든 만큼 너무 힘들었는데 바로 해결이 되네요..
파일처리를 비롯한 c언어 개념 공부를 더 탄탄히 해야겠어요ㅜㅜ
다시 한 번 감사합니다!!

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.