숫자만 입력받기 C언어

momark의 이미지

printf("입력 : ");
scanf("%d",&a);
printf("출력 : %d\n",a);
일 때 숫자만 입력하고 숫자외의 나머지는 오류처리 하고싶은데 어떻게 하나요

익명 사용자의 이미지

if (isdigit(a)) {
    printf("출력");
}
else {
    printf("오류");
}
dragon01254의 이미지

아스키코드를 참고하시면 입력하는 숫자들도, 아스키코드의 다른 문자들과 같이 숫자로 나타내어짐을 알 수 있습니다.
이를 이용하시면 될 듯 하네요.
단점은 하나의 수만 입력하면 가능하지만 십의 자리가 넘어가는 숫자들은 이 방법으로 검사하지 못한다는 겁니다.

kaydash의 이미지

문자로 받으신후에 처리하세요

문자로 받고서 for문을 돌면서 isdigit 이 false일때 오류문을 주고

모두 검사해서 true인경우에

itoa함수로 변환하세요.

HDNua의 이미지

1. 가장 안전한 방법은 kaydash님의 방법대로 문자열로 받는 겁니다.

2. windows에서 visual studio만 이용한다면, (정확히는 visual studio의 컴파일러만 이용한다면)
C로 작성하는 경우 다음과 같이 입력 버퍼를 비우는 걸로 해결할 수 있습니다.

void clearInputBuffer1(FILE *fp) { // 가장 유명한 방법이지만 다른 OS에서 동작하는 게 보장되지 않습니다.
 fflush(fp); // fp가 가리키는 파일 포인터 스트림을 비웁니다.
}
void clearInputBuffer2(FILE *fp) { // 버퍼를 비우려는 파일 스트림에 대해
 while (stdin->_cnt) { // 입력 버퍼에 문자가 남지 않을 때까지
  getchar(); // 문자를 읽고 버립니다.
 } // Mac OS X의 Xcode를 이용할 때는 _cnt 멤버 대신 _r 멤버로 쓰면 되더라구요.
}
void clearInputBuffer3(FILE *fp) { // 스트림이 파일 포인터임을 이용하여
 fseek(fp, 0, SEEK_END); // 파일의 끝으로 파일 포인터를 옮깁니다.
}
 
// usage
int main() {
 int input;
 void (*clearInputBuffer)(FILE *) = clearInputBuffer1;
 scanf("%d", &input);
 clearInputBuffer(stdin); // 표준 입력 스트림에 대해 버퍼를 비운다
 scanf("%d", &input);
 return 0;
}

-----
하지만 역시 문자열로 받고 수로 변환하는 게 제일 낫습니다.

저는 이렇게 생각했습니다.

HDNua 의 이미지

#include
#include //exit()
void correctNumber();
void distinguishingNumAndChar();
void main(){
//두개 중 하나만 실행되게 주석처리하여 하나씩 실행해 보세요.
correctNumber();
//distinguishingNumAndChar();
}
void distinguishingNumAndChar(){
int k, i = 1;
/*if you use 'char' type. you can use number of 'ascii' code*/
while (i){
printf("1. inputGameNum(1~9), 0. Exit: :");
scanf_s("%d", &k);
while (getchar() != '\n'); //scanf_s clear up buffer
if (k > 9 || k < 0){
printf("Out of Menu. Try again.\n\n");
}
else{
printf("Input Number is %d, \nProgram %d is loading…\n\n", k, k);
}
if (k == 0){
printf("System Exit\n\n");
exit(0);
}

}
}
void correctNumber(){
int n;
while (1){
printf("1. 야구영상(1) 2. 야팔영상(2). 3. 종료(0) :");
scanf_s(" %d", &n);
while (getchar() != '\n'); //scanf_s 버퍼 비우기, 밀림 막음
if (n > 2 || n < 0){
n = 3; // 0~2 사이의 메뉴 값이 아니라면 defalut로 보내기
}
switch (n) {
case(1) : {
printf("1. 야구 프로그램 실행\n\n");
break;
}
case(2) : {
printf("2. 야사 프로그램 실행\n\n");
break;
}
case(0) : {
printf("0. 시스템 종료");
exit(0); // #include
}
default: {
printf("님하 그런 메뉴는 없어효\n\n");
break;
}
}
}
}

댓글 달기

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