2009/10/14 17:59 D.B./C/C++

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

#define MAXLINE 100

void read_in(char s[]);
int calc(char *s);

int main()
{
 char line[MAXLINE];
 read_in(line);
 printf("Result = %d\n", calc(line));
 return 0;
}

void read_in(char s[])
{
 int c, i=0;
 printf("Input an equation: ");
 while ((c=getchar()) != '\n')
  s[i++]=c;
 s[i]='\0';
}

int calc(char *s)
{
 int num1=0, num2=0, ret;
 char c, op;

 c=*s++;
 while (isdigit(c))
 {
  num1=10*num1+(c-'0');
  c=*s++;
 }
 op=c;
 c=*s++;
 while (isdigit(c))
 {
  num2=10*num2+(c-'0');
  c=*s++;
 }

 switch (op)
 {
 case '+' :
  ret = num1+num2;
 break;
 case '-' :
  ret = num1-num2;
 break;
 case '*' :
  ret = num1*num2;
 break;
 case '/' :
  ret = num1/num2;
 break;
 default:
  printf("error: unknown operator %c\n", op);
 exit(1);
 }
 return ret;
}



num1 op num2 만 계산되므로,

stack 를 이용한 infix to postfix 를 적용한 후,

깔삼한 계산기를 두들겨 볼까,,



저작자 표시 비영리 동일 조건 변경 허락

'D.B. > C/C++' 카테고리의 다른 글

A op B 형 사칙연산 계산기  (0) 2009/10/14
fflush  (0) 2009/09/20
문자열 버블정렬  (0) 2008/06/02
15행 파스칼 삼각형  (0) 2008/06/02
배열원소 비교 함수  (0) 2008/05/26
2차원 배열의 최대원소와 최소원소를 찾기  (0) 2008/05/25
posted by 은풍
TAG C언어
2009/09/20 21:29 D.B./C/C++
 fflush( stdin );
 
scanf 를 통하여
abc def  라는 입력을 할 경우,
abc 끝에는 문자열의 끝을 의미하는 null character인 ' \0 '이 삽입된다.

따라서 def 대신 '\0'이 입력되어 버그가 발생



출처 : MSDN Library(링크)
fflush

Flushes a stream.

int fflush( 
   FILE *stream 
);
stream

Pointer to FILE structure.

fflush returns 0 if the buffer was successfully flushed. The value 0 is also returned in cases in which the specified stream has no buffer or is open for reading only. A return value of EOF indicates an error.

crt_fflush.c
#include <stdio.h>
#include <conio.h>
int main( void )
{
   int integer;
   char string[81];
   // Read each word as a string.
   printf( "Enter a sentence of four words with scanf: " );
   for( integer = 0; integer < 4; integer++ )
   {
      scanf_s( "%s", string, sizeof(string) );     
      printf( "%s\n", string );
   }
   // You must flush the input buffer before using gets.
   // fflush on input stream is an extension to the C standard
   fflush( stdin );  
   printf( "Enter the same sentence with gets: " );
   gets_s( string, sizeof(string) );
   printf( "%s\n", string );
}
저작자 표시 비영리 동일 조건 변경 허락

'D.B. > C/C++' 카테고리의 다른 글

A op B 형 사칙연산 계산기  (0) 2009/10/14
fflush  (0) 2009/09/20
문자열 버블정렬  (0) 2008/06/02
15행 파스칼 삼각형  (0) 2008/06/02
배열원소 비교 함수  (0) 2008/05/26
2차원 배열의 최대원소와 최소원소를 찾기  (0) 2008/05/25
posted by 은풍
TAG C언어
2008/06/02 20:55 D.B./C/C++

/* 실습1
bubble_string(char *s) 함수를 작성하라.
이 함수는 문자열 s에 대해 버블정렬을 수행한다.
xylophone 의 출력결과는 ehlnoopxy 다.
*/

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

//문자열을 버블정렬하는 함수
void bubble_string(char *s)
{
 int i, j;
 int n=strlen(s);  // 문자열의 길이를 찾음
 char tmp;
 
 for (i=0; i<n-1; i++)  // 문자열 길이만큼 루프
  for(j=n-1; j>i; j--) // 각 원소의 크기를 비교
   if( s[j-1]>s[j] ) // 버블정렬 루틴
   {
    tmp=s[j-1];
    s[j-1]=s[j];
    s[j]=tmp;
   }
   /*if( *(s+ j-1) > *(s+ j) ) // 배열이 아닌 포인터로 연산 조건
   {
    tmp=*(s+ j-1);
    *(s+ j-1)=*(s+ j);
    *(s+ j)=tmp;
   }*/
}

void main()
{
 char str[]="xylophone";
 printf("before sorting: %s\n", str);
 bubble_string(str);    // 버블정렬로 배열을 보냄
 printf("after sorting : %s\n", str);
}


 

저작자 표시 비영리 동일 조건 변경 허락

'D.B. > C/C++' 카테고리의 다른 글

A op B 형 사칙연산 계산기  (0) 2009/10/14
fflush  (0) 2009/09/20
문자열 버블정렬  (0) 2008/06/02
15행 파스칼 삼각형  (0) 2008/06/02
배열원소 비교 함수  (0) 2008/05/26
2차원 배열의 최대원소와 최소원소를 찾기  (0) 2008/05/25
posted by 은풍
TAG C언어
2008/06/02 20:51 D.B./C/C++

/* 실습 #4 chapter 9
파스칼의 삼각형은 (x+y)^n을 전개하였을 때 나타나는 각 항의 계수를 알아내는데 사용된다.
파스칼의 삼각형을 저장하는 2차열 배열을 생성하라.
  출력결과 (15행)
  1
  1 1
   |
  1 14 91
*/

#include <stdio.h>

#define NUM 15  // 15행을 위한 정의

void main()
{
 int arr[NUM][NUM]={0}; // 2 by 2 행렬 정의 및 0으로 초기화
 int i, j;
 
 for(i=0; i<NUM; i++) // 행이 증가
 {
  arr[i][0]=1;  // 각 행의 0번째 원소를 1로 셋팅
  
  for(j=0; j<i+1; j++) // 각 행의 열을 증가
  {
   if(j!=0 && j<i)  // 열의 0 및 마지막 번째를 제외하고,
    arr[i][j]=arr[i-1][j-1]+arr[i-1][j]; // 파스칼 삼각형 연산 수행
   if(j!=0 && j==i) // 각 열의 마지막 번째 원소는
    arr[i][j]=1; // 1로 셋팅
   
   printf("%5d", arr[i][j]); // 각 열의 원소마다 5자리에 맞추어 출력
  }
  printf("\n");     // 한 행이 끝나면 개행함
 }
}

 



 

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/05/26 20:54 D.B./C/C++

/* 실습 #3
2개의 정수 배열 a, b를 받아서 대응되는 배열원소가 같은지를 검사하는 함수
int array_equal(int a[], int b[], int size) 를 작성하고 테스트하라.
이 함수는 전체 원소가 같다면 1을 반환하고, 그렇지 않으면 0을 반환한다.
*/

#include <stdio.h>

// 두 배열의 원소가 같은지 확인하는 함수
int array_element_equal(int a[], int b[], int size)
{
 int i, j, s1=0, s2=0;
 
 for(i=0; i<size; i++) 
  for(j=0; j<size; j++) 
   if( a[i]==b[j] )
   {     // a에 대한 b의 각 원소가 같으면
    s1++;   // s1을 증가
    break;
   }

 for(i=0; i<size; i++)
  for(j=0; j<size; j++)
   if( b[i]==a[j] )
   {    // b에 대한 a의 각 원소가 같으면
    s2++;    // s2를 증가
    break;
   }
     
 if (s1==s2 && s1==size)   // s1과 s2의 증가한 값이 같고
  return 1;     // s의 값이 size와 같다면, match
 else
  return 0;
}

// 두 배열의 동일 인덱스에 있는 원소가 같은지 확인하는 함수
int array_element_of_index_equal(int a[], int b[], int size)
{
 int i;
 
 for(i=0; i<size; i++)
  if( a[i]!=b[i] )   // 동일한 index의 a, b 원소가 다르면
   return 0;    // miss match
  
 return 1;      // otherwise.
}

void main()
{
 int a[]={1,2,3,4,5};
 int b[]={2,1,3,4,5};
 int ret;
 
 ret = array_element_equal(a, b, 5);
 
 if(ret == 1) printf("a[], b[]'s elements match.\n");
 else   printf("a[], b[]'s elements not match.\n");
 
 printf("\n");
 
 ret = array_element_of_index_equal(a, b, 5);
 
 if(ret == 1) printf("a[], b[] is equal.\n");
 else   printf("a[], b[] is not equal.\n");
}


 

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/05/25 20:54 D.B./C/C++

/*************************************************
  9장 연습문제 8번
  2차원 배열의 최대원소와 최소원소를 찾는 프로그램
 *************************************************/

#include <stdio.h>

//최대원소 찾는 함수
int _max(int a[][3], int n, int m)
{
 int i, j;
 int max = a[0][0];   // max의 초기값을 지정
 for(i=0; i<n; i++)   // 2차원배열을 순환하면서 값 비교
  for(j=0; j<m; j++)
   if(a[i][j] > max) // 원소값이 max보다 크면
    max = a[i][j]; // max 값 교체
   
   return max;
}

//최소원소 찾는 함수
int _min(int a[][3], int n, int m)
{
 int i, j;
 int min = a[0][0];   // min의 초기값을 지정
 for(i=0; i<n; i++)   // 2차원배열을 순환하면서 값 비교
  for(j=0; j<m; j++)
   if(a[i][j] < min) // 원소값이 min보다 작으면
    min = a[i][j]; // min 값 교체
   
   return min;
}
/* 미완성
int _mid(int a[][3], int n, int m)
{
 int i, j;
 int max=a[0][0];
 int min=a[0][0];
 int mid=a[0][0];

 for (i=0; i<n; i++)
 {
  for (j=0; j<n; j++)
  if(a[i][j]>max){
   if(max>min)
    mid=max;
   max=a[i][j];
  }
  else
   min=a[i][j];
  }
 }
 return mid;
}*/


void main()
{
 int a[3][3]={ {7,3,-9}, {1,-5,8}, {8,3,10}};
 
 printf("max = %d\n", _max(a,3,3));
 // printf("mid = %d\n", _mid(a,3,3));
 printf("min = %d\n", _min(a,3,3));
}


 

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/05/20 20:52 D.B./C/C++

#include <stdio.h>

void swap(double *a, double *b)
{
 double tmp = *a;
 *a = *b;
 *b = tmp;
}

double max(double a[], int n)
{
 int i;
 double max = a[0];
 for(i=1; i<n; ++i){
  if(a[i] > max)
   max = a[i];
 }
 return max;
}

double min(double a[], int n)
{
 int i;
 double min = a[0];
 for(i=1; i<n; ++i){
  if(a[i] < min)
   min = a[i];
 }
 return min;
}

double mid(double a[], int n) /* using Bubble sort */
{
 int i, j;
 for(i=0; i<n-1; ++i) {
  for(j=n-1; i<j; --j) {
   if(a[j-1] > a[j])
    swap(&a[j-1], &a[j]);
  }
 }
 return a[n/2];
}

void _selection(double a[], int n)
{
 int i, j, min;
 
 for ( i = 0 ; i < n - 1 ; i++ ) {
  min = i;
  for ( j = i + 1 ; j < n ; j++ ){
   if ( a[j] < a[min] )
    min = j;
  }
  swap( &a[min], &a[i] );  
 }
}

void insertion(double a[], int n)
{
 int i, j;
 double tmp;
 
 for(i=1;i<n;i++)
 {
  tmp = a[i];  
  for(j=i;j>0;j--) //삽입할 위치를 찾음
  {
   if(a[j-1]>tmp) //뒤로 한간 밀기 위한 조건
    a[j]=a[j-1];
   else
    break;
  }
  a[j]=tmp;   //삽입 함
 }
 
}

void print_array(double a[], int n)
{
 int i;
 for(i=0; i<n; i++){
  printf("%.1f ", a[i]);
 }
 printf("\n\n");
}

void main()
{
 double a[] = {7.1, 3.5, 99.3, 3, -5};
 double b[] = {4.5, 2, -5, -3.8, 55};
 // printf("max num is %.1f\n", max(a, 5));
 // printf("min num is %.1f\n", min(a, 5));
 // printf("mid num is %.1f\n", mid(a, 5));
 
 printf("original a[] is ");
 print_array( a, 5 );
 _selection( a, 5 );
 printf("selection sorted a[] is ");
 print_array( a, 5 );
 
 printf("original b[] is ");
 print_array( b, 5 );
 insertion( b, 5 );
 printf("insertion sorted b[] is ");
 print_array( b, 5 );
}

 

 

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/05/09 20:52 D.B./C/C++

/*
4. 정수배열의 원소 중에서, 짝수의 합과 홀수의 합을 구하는 함수를 작성하라.
함수정의 시 아래의 코드가 포함되도록 하라.

void sum(int a[],
        int n,   // n is the size of a[]
        int *even_element_sum_ptr,
        int *odd_element_sum_ptr)
{
 ...
}
*/

#include <stdio.h>

void sum(int a[], int n, int *even_element_sum_ptr, int *odd_element_sum_ptr)
{
 int i;
 
 for(i=0;i<n;i++)
 {
  if(a[i]%2!=0)
   *odd_element_sum_ptr += a[i];
  else
   *even_element_sum_ptr += a[i];
 }
}

void main()
{
 int a[]={2,5,3,4,2};
 int n=5;
 int odd_element_sum=0;
 int even_element_sum=0;
 
 sum(a, n, &even_element_sum, &odd_element_sum);
 
 for(n=0; n<5; n++)
  printf("%d, ", a[n]);
 printf("\n");
 printf("even : %d, odd : %d\n", even_element_sum, odd_element_sum);
}


저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/04/10 20:50 D.B./C/C++

/*8.7 세 개의 문자형 변수에 저장되어 있는 값을 알파벳 순서로 정렬하는
함수를 작성하라. 예를 들어, 변수 c1, c2, c3가 문자형 변수이고,
각각 ‘C', 'B', 'D'가 저장되어 있다고 할 때, 함수 order_chars(&c1, &c2, &c3)의
호출은 c1, c2, c3의 값이 각각 ’B', 'C', 'D'가 되게 한다.
작성함수를 테스트할 수 있는 프로그램을 작성하여 테스트해 보라.
*/

#include <stdio.h>

void order_chars(char *, char *, char *)
{
 char tmp;
 tmp=*p1;
 *p1=(*p1<*p2)?*p1:*p2;
 if(tmp!=*p1)
  *p2=tmp;
 tmp=*p1;
 *p1=(*p1<*p3)?*p1:*p3;
 if(tmp!=*p1)
  *p3=tmp;
 tmp=*p2;
 *p2=(*p2<*p3)?*p2:*p3;
 if(tmp!=*p2)
  *p3=tmp;
 
}

void main()
{
 char c1='C',c2='B',c3='D';
 
 printf("%c, %c, %c\n", c1,c2,c3);
 order_chars(&c1, &c2, &c3);
 printf("%c, %c, %c\n", c1,c2,c3);
}

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어
2008/04/10 20:49 D.B./C/C++

/* 8.6 다음 예를 참조하여 다섯 개의 문자형 변수에 저장되어 있는 값을
원형(circular)으로 이동(shift)시키는 프로그램을 작성하라.
다섯 개의 변수 c1, c2 ... c5가 char형이고, 이들의 초기값이
각각 ‘A', 'B', 'C', 'D', 'E'라고 가정하자.
함수 shift(&c1, &c2, &c3, &c4, &c5)가 호출되면 변수 c1, c2 ... c5의 값은
각각 'B', 'C', 'D', 'E', 'A'가 된다. 함수의 정의는 다음과 같이 시작하도록 하고,
void shift(char *p1, char *p2, char *p3, char *p4, char *p5)
{
    ....
이를 다섯 번 호출하면서 매 호출 시마다 각 변수들의 값을 출력하도록 하여
그 출력이 BCDEA, CDEAB, DEABC, EABCD, ABCDE가 되는지 확인하라.
*/

#include <stdio.h>
#define NUM 5

void shift(char *p1, char *p2, char *p3, char *p4, char *p5);

void main()
{
 int i;
 char c1='A',c2='B',c3='C',c4='D',c5='E';
 
 printf("%c, %c, %c, %c, %c\n", c1,c2,c3,c4,c5);
 for (i=0;i<NUM; i++)
 {
  shift(&c1,&c2,&c3,&c4,&c5);
  printf("%c, %c, %c, %c, %c\n", c1,c2,c3,c4,c5);
 }
}

void shift(char *p1, char *p2, char *p3, char *p4, char *p5)
{
 char tmp;
 tmp=*p1;
 *p1=*p2;
 *p2=*p3;
 *p3=*p4;
 *p4=*p5;
 *p5=tmp;
}

 

저작자 표시 비영리 동일 조건 변경 허락
posted by 은풍
TAG C언어