'\n' 값이 들어 가는것 같습니다만 어디서 들어가는건지?

hurryon의 이미지

'\n' 값이 들어 가는것 같습니다만 어디서 들어 가는지 알수가 없어서 소스을
올리게 되었습니다. 간단하게 주소록을 만들어 볼까 하는데 처음부터 이렇게
막히게 되네요.

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char name[10];
    char address[30];
    char phone[20];
    char cell_phone[20];
    char email[30];
} node;

node address;

void init();
void add();
void modify();
void delete();
void search();
void display();
int get_option();

main()
{
    int option;

    init();
     
    do
    {
        option = get_option();
    
        switch(option)
        {
            case 1:
                add();
                break;
    
            case 2:
                modify();
                break;

            case 3:
                delete();
                break;

            case 4:
                search();
                break;

            case 5:
                display();
                break;

            case 6:
                printf("-------------------------종료----------------------------\n");
                break;

            default:
                break;
        }

    } while(option <= 5);

}

void init()
{
    printf("-------------------------------------------------------\n");
    printf("------------------주소록 프로그램(file)----------------\n");
    printf("-----------------**----------------\n");
    printf("-------------------------------------------------------\n");
}

int get_option()
{
    int option;
    char c;

    printf("-------------------------------------------------------\n");
    printf("1. 입력  2. 수정  3. 삭제  4. 찾기  5. 출력  6. 종료 \n");
    printf("모드: ");

    c = fgetc(stdin);

    return c - '0';
}

void add()
{
    node tmp;

    char name[10];
    char address[30];
    char phone[20];
    char cell_phone[20];
    char email[30];

    printf("\n-----------------------입력----------------------종료(!)\n");

    for(;;)
    {
        printf("이름: ");
        fgets(name, sizeof(name), stdin);
        name[strlen(name)-1] = '\0';

        printf("%s", name);
    }
}

void modify()
{

}

void delete()
{

}

void search()
{

}

void display()
{

}

결과는 다음과 같습니다.

[root@note file]# gcc -o address_file address_file.c
[root@note file]# ./address_file
-------------------------------------------------------
------------------주소록 프로그램(file)----------------
-----------------**----------------
-------------------------------------------------------
-------------------------------------------------------
1. 입력 2. 수정 3. 삭제 4. 찾기 5. 출력 6. 종료
모드: 1

-----------------------입력----------------------종료(!)
이름: 이름: 이종혁
이종혁이름: 이종혁
이종혁이름: 이종혁
이종혁이름:
[root@note file]#

보시면 알겠지만 처음에 바로 '\n' 값이 들어 가는것 같습니다. 그래서
처음에 이름을 바로 입력 받지 못하고 있습니다.

어디서 들어 가는지?

notfound의 이미지

아뭏든, 눈에 뜨이는 곳이 하나 있네요..

man fgets 해보시길..

Sometime, it is better for you to restart than recover.

ihavnoid의 이미지

fgets() 함수는 read할때 끝에 (사용자가 입력한)엔터가 붙는답니다...^^

Consider the ravens: for they neither sow nor reap; which neither have storehouse nor barn; and God feedeth them: how much more are ye better than the fowls?
Luke 12:24

realian의 이미지

이 문제를 scanf의 관계해서 토의되었던 내용이 있군요.

검색.. 에서 scanf로 검색해서 위쪽인가 나오는 게시물을 보세요.

처음 추천된 방법은 fflush(stdin); 을 해주는거 였는데 위험한 방법이라고 하시네요..

다른 방법으로 scanf(%d\n"); 이나 getchar(); 를 해서 '\n'을 소비하는 방법등이 있다는군요..

자세한 내용은 게시물을 참고하세요..

..........No Sig.........|
-------------------+

jilossoju의 이미지

올려주신 내용중 아래의 부분을 참고해 주세요.

[root@note file]# ./address_file
-------------------------------------------------------
------------------주소록 프로그램(file)----------------
-----------------**----------------
-------------------------------------------------------
-------------------------------------------------------
1. 입력 2. 수정 3. 삭제 4. 찾기 5. 출력 6. 종료
모드: 1

-----------------------입력----------------------종료(!)
이름: 이름: 이종혁
이종혁이름: 이종혁
이종혁이름: 이종혁
이종혁이름:
[root@note file]#

위의 내용에서 모드값을 입력하고 엔터를 치게 됩니다.
문제는 모드로 입력된 값을 받는 함수는 fgetc() 입니다.
이 함수는 실제로 1 이라는 값만을 읽어가게 됩니다.
즉, 입력된 엔터는 입력 스트림에 그대로 남아있게 됩니다.
문제는 실제로 이름을 입력받는 fgets() 라는 놈인데.
이놈은 stdin 에서 EOF 나 newline 이 입력될때 까지 읽어오게 됩니다.
그런데 이전 모드값을 입력받은때 남아있던 엔터를 읽어가게 되는 것입니다.
fgetc() 부분을 scanf() 를 사용해서 처리해 보세요.
scanf() 에 대한 내용은 이글 몇개 아래에 올라와 있습니다.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.