반응형

9.2> Converter 클래스를 상속받아 km mile(마일)로 변환하는 KmToMile 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.

<코드>

#include <iostream>

#include <string>

using namespace std;

 

class Converter {

protected:

        double ratio;

        virtual double convert(double src) = 0; //src 다른 단위로 변환한다.

        virtual string getSourceString() = 0; //src 단위 명칭

        virtual string getDestString() = 0; //dest 단위 명칭

public:

        Converter(double ratio) { this->ratio = ratio; }

        void run() {

               double src;

               cout << getSourceString() << " " << getDestString() << " 바꿉니다. ";

               cout << getSourceString() << " 입력하세요>> ";

               cin >> src;

               cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅

        }

};

 

class KmToMile : public Converter{

protected:

        string from; //바뀌어지는 것의 이름

        string to; //바뀐 결과의 이름

public:

        KmToMile(double ratio, string from, string to);

        virtual double convert(double src);

        virtual string getSourceString();

        virtual string getDestString();

};

KmToMile::KmToMile(double ratio,string from="Km",string to="Mile"):Converter(ratio){

        this->from = from;

        this->to = to;

        this->ratio = ratio; //생성자 from,to,ratio 초기화 from to 디폴트는 "Km" "Mile"

}

double KmToMile::convert(double src){return src/ratio;}

string KmToMile::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩

string KmToMile::getDestString() { return to; } //dest스트링 함수 오버라이딩

 

int main(void){

        KmToMile toMile(1.609344); //1 mile 1.609344 Km

        toMile.run();

        return 0;

}

 

<결과창>

                                   


반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

while, do while loop class  (0) 2017.12.31
ForLoopAdder 클래스  (0) 2017.12.31
WonToDollar Class  (0) 2017.12.31
Printer Class  (0) 2017.12.31
ROM RAM class  (0) 2017.12.31
반응형

Open Challenge> 아래< 5-1>을 참고하여 영문 텍스트, 숫자, 몇 개의 특수 문자로 구성되는 텍스트를 모스 부호로 변환하는 프로그램을 작성하라. 모스 부호는 전보를 쳐서 통신하는 시절에 사용된 유명한 코딩 시스템이다. 각 모스 코드들은 하나의 빈칸으로 분리되고, 영문 한 워드가 모스 워드로 변환되면 워드들은 3개의 빈칸으로 분리된다. 실행 예는 다음과 같다. 영문 텍스트를 입력받아 모스 부호로 변환하여 출력하고, 변환이 잘 되었는지 확인하기 위해 다시 모스 부호를 영문 텍스트로 변환하여 원문을 출력한 사례이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <algorithm>
#include <string>
 
using namespace std;
 
class Morse{
private:
    string alphabet[26]; //알파벳의 모스 부호 저장
    string digit[10]; //숫자의 모스 부호 저장
    string slash, question, comma, period, plus, equal; //특수 문자의 모스 부호 저장
public:
    Morse(); //alphabet[], digit[] 배열 및 특수 문자의 모스 부호 초기화
    void text2Morse(string text, string& morse); //영문 텍스트를 모스 부호로 변환
    bool morse2Text(string morse, string& text); //모스 부호를 영문텍스트로 변환
};
Morse::Morse(){
    string Malphabet[26]=".-""-...""-.-.""-.."".","..-.""--.""...."".."".---",
                   "-.-"".-..""--""-.""---",".--.""--.-"".-.""...""-",
                   "..-""...-"".--""-..-""-.--""--.."};
    string Mdigit[10]={"-----"".----""..---""...--""....-"".....""-....""--...""---..""----." };
    slash= "-..-.";    question= "..--..";    comma= "--..--";
    period= ".-.-.-";  plus= ".-.-.";     equal= "-...-"//모스 특수문자 초기화
    int i;
    for(i=0;i<26;i++){alphabet[i]=Malphabet[i];} //모스 알파벳 초기화
    for(i=0;i<10;i++){digit[i]=Mdigit[i];} //모스 숫자 초기화
}
void Morse::text2Morse(string text, string& morse){
    transform(text.begin(),text.end(),text.begin(),tolower); // 입력한 문자열을 전부 소문자로 바꾼다.
    for(int i=0;i<text.length();i++){
        if(text[i]>=97&&text[i]<=122){morse=morse+alphabet[text[i]-97]+" ";} //해당 인덱스가 알파벳일 경우 해당 모스 부호 삽입
        else if(text[i]==' '){morse+="   ";} //해당 인덱스가 공백문자 일경우 공백문자 3개 입력
        else if(text[i]>=48&&text[i]<=57){morse=morse+digit[text[i]-48]+" ";} //해당 인덱스가 숫자 일경우 해당 모스 부호 삽입
        else if(text[i]=='/'){morse=morse+slash+" ";}
        else if(text[i]=='?'){morse=morse+question+" ";}
        else if(text[i]==','){morse=morse+comma+" ";}
        else if(text[i]=='.'){morse=morse+period+" ";}
        else if(text[i]=='+'){morse=morse+plus+" ";}
        else if(text[i]=='='){morse=morse+equal+" ";} //해당 인덱스가 특수문자 일경우 해당 모스 부호 삽입
    }
}
bool Morse::morse2Text(string morse, string& text){
    string regen; //다시 읽을 수 있게 복원한 것을 넣을 스트링
    string sub; // 공백 문자 단위로 자름
    int i;
    int startindex=0//문자를 찾기 시작할 첫번째 index
    int blankindex=-1//공백문자의 index
    int swch=1//모스부호가 무엇인지 검사하는데 사용할 플래그
    while(1){
        swch=1//플래그는 루프 돌때마다 1로 ON
        startindex=blankindex+1//찾기 시작할 인덱스는 공백 인덱스 더하기 1
        blankindex=morse.find(" ",blankindex+1); //전에 찾았던 것을 또 찾으면 안되니 더하기 1을해서 공백문자를 찾는다.
        sub=morse.substr(startindex,blankindex-startindex); // 공백 문자를 제외한 무언가를 나타내는 모스부호 부분만 자른다.
        for(i=0;i<26;i++){
            if(alphabet[i]==sub)
                {regen+=(char)(97+i);
            swch=0;break;}    //알파벳일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            for(i=0;i<10;i++){
                if(digit[i]==sub)
                {regen+=(char)(48+i);
                swch=0;break;}
            } //숫자일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            if(sub==slash){regen+="/";}
            else if(sub==question){regen+="?";}
            else if(sub==comma){regen+=",";}
            else if(sub==period){regen+=".";}
            else if(sub==plus){regen+="+";}
            else if(sub==equal){regen+="=";}
        } //특수문자일 경우 regen에 더한다. 
 
        if(blankindex==morse.length()-1){break;} //여기서 검사하는 이유는 인덱스가 맨 마지막일때 +1,+2,+3 을 검사하면 오류가 나기 때문이다.
        if((morse[blankindex+1]==' ')&&(morse[blankindex+2]==' ')&&(morse[blankindex+3]==' ')){
            regen+=" ";     cout<<regen<<endl//제대로 이어졌나 확인.
            blankindex+=3//공백문자가 연달아 3개 있으면 실제에서는 공백문자 하나를 뜻한다. 이를 검사하기 위함.
        }
        }
    if(regen==text) return true//새로 만든 문자열과 원래 문자열이 같으면 true리턴
    else return false//아니면 false 리턴
}
int main(void){
    Morse m;
    string english;
    string morse;
    cout<<"아래에 영문 텍스트를 입력하세요. 모스 부호로 바꿉니다."<<endl;
    getline(cin,english,'\n'); //개행문자 나올 때까지 문자열 받는다
    m.text2Morse(english,morse); //모스부호로 전환
    cout<<morse<<endl;
    cout<<"모스 부호를 다시 영문 텍스트로 바꿉니다."<<endl;
    if(m.morse2Text(morse,english)) //다시 읽을 수 있는 텍스트로 전환
        cout<<english<<endl//만약 같으면 원래 문자열 출력
    else
        cout<<"오류 발생"<<endl//다르면 오류발생 출력
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
반응형

4.10> 영문자로 구성된 텍스트에 대해 각 알파벳에 해당하는 문자가 몇 개인지 출력하는 히스토그램 클래스 Histogram을 만들어보자. 대문자는 모두 소문자로 변환하여 처리한다. Histogram 클래스를 활용하는 사례와 실행 결과는 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <algorithm> //transform 함수 사용 위함
#include <string>
 
using namespace std;
 
class Histogram{
private:
    string s; //스트링 저장용
public:
    Histogram(string s){(this->s)+=s;} //생성자는 멤버스트링 s에 매개스트링 s를 더한다.
    void put(string s){(this->s)+=s;} //멤버스트링 s에 매개스트링 s를 더한다.
    void putc(char c){(this->s)=s+c;} //멤버스트링 s에 매개 캐릭터 c를 더한다.
    void print(){
        cout<<s<<endl//소문자화 하기전 출력
        transform(s.begin(),s.end(),s.begin(),tolower); //스트링 s를 전부 소문자화 시킴
        cout<<s<<endl//소문자화 한 후 출력
        for(int i=0;i<26;i++){ //알파벳이 26자라서 26번 돌린다.
            int count=0//알파벳 몇번 나왔나 셀 때 사용할 변수
            for(int k=0;k<s.size();k++){ //스트링 전부 순회
                if(s[k]==(i+97)) //아스키코드 97이 'a'라서 97~97+26 은 'a'~'z'를 의미한다. s의 각 문자를 'a'~'z'와 비교
                    count++//만약 s[k]가 i+97과 같으면 count 증가
            }
            cout<<(char)(i+97)<<" ("<<count<<")    :    "//출력
 
            for(int j=0;j<count;j++//count 수만큼 별 출력
                {cout<<"*";}
            cout<<endl//한줄 내린다.
        }
    }
};
 
int main(void){
    Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
    elvisHisto.put("falling in love with you");
    elvisHisto.putc('-');
    elvisHisto.put("Elvis Presley");
    elvisHisto.print();
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
Circle, CircleManager 클래스  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
반응형

4.9> 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
 
using namespace std;
 
class Circle{ 
private:
    int radius;
    string name;
public:
    void setCircle(string name, int radius){ //멤버 name과 radius를 set해줌.
        this->name=name; this->radius=radius;
    }
    double getArea(){return radius*radius*3.14;} //원의 면적 리턴
    string getName(){return name;} //원의 이름 리턴
};
 
class CircleManager{
private:
    Circle *p; //Circle형 포인터 p
    int size;
public:
 
    CircleManager(int size){ //컨스트럭터
        this->size=size
        p=new Circle[size]; //size크기만큼의 Circle형 동적 객체 배열 생성
        int radius; string name;
        for(int i=0;i<size;i++){
            cin.ignore(100,'\n'); //cin은 개행문자를 버퍼에 남겨놓기 때문에 버퍼에서 비워줘야 한다.
                                //그렇지 않으면 다음 루프의 getline이 개행문자 + 입력한 문자열을 받아버린다.
            cout<<"원 "<<i+1<<"의 이름과 반지름 >>";
            getline(cin,name,' '); // space를 delimeter로 설정하여 이름을 받는다.
            cin>>radius;     //radius는 cin으로 받는다.
            p[i].setCircle(name,radius); //Circle을 set 해줌.
        }
    cin.ignore(); //마지막 개행문자 버퍼에서 제거
    }
    ~CircleManager(){delete []p;} //동적 Circle 객체 배열 해당 메모리 힙으로 반환
    void searchByName(){
        string cmp;
        cout<<"검색하고자 하는 원의 이름>> ";
        getline(cin,cmp,'\n'); //cmp를 getline으로 개행문자 나올때까지 받는다.
        for(int i=0;i<(this->size);i++){
            if(cmp==(p[i].getName()))  //cmp와 i번째 동적circle의 name이 같으면
            {cout<<"도넛의 면적은 "<<p[i].getArea()<<endl//i번째 동적circle의 area 반환
            break;}
        }
    }
    void searchByArea(){
        int area;
        cout<<"최소 면적을 정수로 입력하세요>> ";
        cin>>area; //area를 받는다.
        cout<<area<<"보다 큰 원을 검색합니다."<<endl;
        for(int i=0;i<(this->size);i++){ //동적 객체 배열 전부 순회하여 area보다 
            if(p[i].getArea()>area) //p번째 circle 객체의 넓이가 크면 출력
                cout<<p[i].getName()<<"의 면적은 "<<p[i].getArea()<<", ";
        }
        cout<<endl//개행 출력
    }
};
 
int main(void){
    int size;
    cout<<"원의 개수 >> " ; 
    cin>>size//원의 개수 정함
    CircleManager m(size); //CircleManager객체 생성
    m.searchByName(); //Name으로 찾기
    m.searchByArea(); //특정 Area 초과인것 찾기
    
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
반응형

4.3> string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 입력받고 글자 하나만 랜덤하게 수정하여 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdlib> //random 사용 위함
#include <ctime> //srand 사용 위함
#include <string> //string 객체 사용 위함
 
using namespace std;
 
int main(void){
    string s; //string 객체 s
    srand((unsigned)time(0)); //시드값 설정
    
    cout<<"아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)"<<'\n';
    while(true){ //무한루프
    cout<<">>";
    getline(cin,s,'\n'); //delimeter '\n'으로 한 줄 받아 s에 저장
    if(s=="exit"//s가 exit면 루프 탈출
        break;
    int rand_index=(rand())%(s.length()); //rand_index에 임의 인덱스 저장(s.length로 나눈 나머지는 무조건 0~length-1이 나옴)
    //조심해야 할것은 알파벳만 인덱스에 포함되는 것이 아니라 공백문자, 마침표와 같은 문자도 포함된다.
    int Daeso=rand()%2//글자를 바꾸는데 소문자로 바꿀 것인지 대문자로 바꿀 것인지 랜덤으로 정한다.
    if(Daeso==0//대문자로 정해짐
    s[rand_index]=(char)((rand()%26)+65); //아스키코드 65~90 대문자 알파벳
    else if(Daeso==1//소문자로 정해짐
    s[rand_index]=(char)((rand()%26)+97); //아스키코드 97~122 소문자 알파벳
    cout<<s<<endl//s출력
    }
    return 0;
}
 
cs



반응형
반응형

다수의 클래스를 선언하고 활용하는 간단한 문제이다. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 4개의 클래스 Add, Sub, Mul, Div 를 만들고자 한다. 이들은 모두 공통으로 다음 멤버를 가진다. Int 타입 변수 a,b : 피연산자 void setValue(int x, int y)함수 : 매개 변수 x,y를 멤버 a,b에 복사 int calculate() 함수 : 연산을 실행하고 결과 리턴 main()함수는 Add, Sub, Mul, Div 클래스 타입의 객체 a, s, m, d를 생성하고 ,아래와 같이 키보드로부터 두 개의 정수와 연산자를 입력받고 a, s, m, d 객체 중에서 연산을 처리할 객체의 setValue() 함수를 호출한 후 calculate()를 호출하여 결과를 화면에 출력한다. 프로그램은 무한 루프를 돈다




< cpp 파일에 전부 넣은 것>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
using namespace std;
/*각 클래스의 함수들을 직접 구현하는 구현부 cpp파일*/
class Add{
private:
    int a,b;  //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y); // 인자 대입
    int calculate(); //계산
};
class Sub{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Mul{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Div{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
void Add::setValue(int x,int y){ //값 지정 x를 a에, y를 b에 대입한다.
    a=x;
    b=y;
}
int Add::calculate(){ //더하기 연산
    return a+b;
}
void Sub::setValue(int x,int y){
    a=x;
    b=y;
}
int Sub::calculate(){ //빼기 연산
    return a-b;
}
void Mul::setValue(int x,int y){
    a=x;
    b=y;
}
int Mul::calculate(){ //곱하기 연산
    return a*b;
}
void Div::setValue(int x,int y){ 
    a=x;
    b=y;
}
int Div::calculate(){//나누기 연산
    return a/b;
}
int main(void){
    while(1){
        int x;
        int y;
        char opr; //operator를 구별하기 위한 대입용 캐릭터형 변수
        Add a; Sub s; Mul m; Div d; //각 클래스 객체 생성
        cout<<"두 정수와 연산자를 입력하세요>>";
        cin>>x>>y>>opr;
        if(opr=='+'){ //opr이 +면
            a.setValue(x,y); //operand 값 set 해주고
            cout<<a.calculate()<<endl//계산값 출력
        }
        else if(opr=='-'){ //opr이 -면
            s.setValue(x,y);
            cout<<s.calculate()<<endl;
        }
        else if(opr=='*'){ //opr이 *면
            m.setValue(x,y);
            cout<<m.calculate()<<endl;
        }
        else if(opr=='/'){ //opr이 /면
            d.setValue(x,y);
            cout<<d.calculate()<<endl;
        }
    }
    return 0;
}
 
cs

<코드-헤더파일 Calcuator.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef CALC_H //헤더 파일 중복 include 방지용
#define CALC_H
 
class Add{
private:
    int a,b;  //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y); // 인자 대입
    int calculate(); //계산
};
class Sub{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Mul{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
class Div{
private:
    int a,b; //operand로 쓸 int형 변수 a,b
public:
    void setValue(int x,int y);
    int calculate();
};
#endif
 
cs

<코드-클래스cpp파일 Calculatop.cpp>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "Calculator.h" //선언부 include
#include <iostream>
using namespace std;
/*각 클래스의 함수들을 직접 구현하는 구현부 cpp파일*/
 
void Add::setValue(int x,int y){ //값 지정 x를 a에, y를 b에 대입한다.
    a=x;
    b=y;
}
int Add::calculate(){ //더하기 연산
    return a+b;
}
void Sub::setValue(int x,int y){
    a=x;
    b=y;
}
int Sub::calculate(){ //빼기 연산
    return a-b;
}
void Mul::setValue(int x,int y){
    a=x;
    b=y;
}
int Mul::calculate(){ //곱하기 연산
    return a*b;
}
void Div::setValue(int x,int y){ 
    a=x;
    b=y;
}
int Div::calculate(){//나누기 연산
    return a/b;
}
 
cs



<코드-메인cpp파일 main.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include "Calculator.h" //calculator 내에 클래스 사용 위한 include
using namespace std;
 
int main(void){
    while(1){
        int x;
        int y;
        char opr; //operator를 구별하기 위한 대입용 캐릭터형 변수
        Add a; Sub s; Mul m; Div d; //각 클래스 객체 생성
        cout<<"두 정수와 연산자를 입력하세요>>";
        cin>>x>>y>>opr;
        if(opr=='+'){ //opr이 +면
            a.setValue(x,y); //operand 값 set 해주고
            cout<<a.calculate()<<endl//계산값 출력
        }
        else if(opr=='-'){ //opr이 -면
            s.setValue(x,y);
            cout<<s.calculate()<<endl;
        }
        else if(opr=='*'){ //opr이 *면
            m.setValue(x,y);
            cout<<m.calculate()<<endl;
        }
        else if(opr=='/'){ //opr이 /면
            d.setValue(x,y);
            cout<<d.calculate()<<endl;
        }
    }
    return 0;
}
 
cs




반응형
반응형

텍스트 파일에서 특정한 단어를 찾아서 다른 단어로 변경하여 출력 파일에 쓰는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
#define ROW 20
#define COL 20
int main(void)
{
    FILE *fpr=NULL;
    FILE *fpw=NULL;
    char tok[ROW][COL];
    char rpl[SIZE];
    char sub[SIZE];
    char line[SIZE];
    char *token;
    int count; int i;
    if((fpr=fopen("origin.txt","r"))==NULL)
    {
        printf("파일오픈실패1\n");
        exit(1);
    }
    if((fpw=fopen("change.txt","a"))==NULL)
    {
        printf("파일오픈실패2\n");
        exit(1);
    }
    printf("바뀔 단어를 입력하세요: ");
    gets(rpl);
    printf("대신 넣을 단어를 입력하세요: ");
    gets(sub);
    while(!feof(fpr))
    {
        fgets(line,SIZE,fpr);
            count=0;
            token=strtok(line," "); //토큰 분리
            while(token!=NULL)
            {
                strcpy(tok[count],token); //토큰을 이차원배열로 삽입
                if(strcmp(tok[count],rpl)==0//이차원배열과 rpl 비교
                {strcpy(tok[count],sub);} //같을시 이차원배열에 sub 삽입
                count++//카운트는 이차원배열 개수 세는데 사용
                token=strtok(NULL," \n"); //연속적 토큰 분리
            }
        for(i=0;i<count;i++)
        {
            strcat(tok[i]," "); //자르는 것으로 공백문자사용 했기에 다시 붙여줘야함
            fputs(tok[i],fpw);
        }
        fputs("\n",fpw); //자르는 것으로 개행문자 사용했으므로 다시 붙여줌
    } //이프로그램은 불완전한데 쉼표나 마침표가 붙어있으면 검색을 하지 못한다.
    fclose(fpr); //그렇다고 자르는 것으로 쉼표를 추가한다고 해도 그 쉼표를
    fclose(fpw); // 제자리에 다시 박아놓는 방법을 찾지 못하였다.(어떤 걸로 잘랐는지 어떻게 구분할까?)
    return 0;
    }
cs




이프로그램은 불안전합니다. 공백문자와 개행문자로 분리된 일반적인 단어는 잡아낼 수 있지만 

쉼표나 마침표가 붙어있는 문자는 잡아낼 수가 없습니다.  더 좋은 방법이 있으면 알려주세요!




반응형
반응형

파일에서 특정한 단어를 찾아서 파일 이름과 단어가 위치한 줄 번호를 출력하는 프로그램을 작성하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
int main(void)
{
    FILE *fp=NULL;
    char name[SIZE];
    char word[SIZE];
    char line[SIZE];
    int num=0;
    printf("파일 이름: ");
    gets(name);
    if((fp=fopen(name,"r"))==NULL)
    {
        printf("파일오픈오류\n");
        exit(1);
    }
    printf("탐색할 단어: ");
    gets(word);
    while(!feof(fp))
    {
        num++;
        fgets(line,SIZE,fp);
            if(strstr(line,word)!=NULL)
            {
                printf("%s: %d    %s",name,num,line);
            }
    }
    fclose(fp);
    return 0;
}
cs






반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C언어' 카테고리의 다른 글

명령어 라인으로 텍스트 파일 합치기  (0) 2017.02.18
단어 바꾸기  (0) 2017.02.18
텍스트 파일과 이진 파일  (0) 2017.02.17
도서 관리 프로그램  (0) 2017.02.17
줄 번호 붙이기  (0) 2017.02.17
반응형

텍스트 파일을 읽어서 각 줄의 앞에 줄 번호를 붙이는 프로그램을 작성하라. 줄 번호는 폭이 6이고 오른쪽 정렬되도록 하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
int main(void)
{
    FILE *fp = NULL;
    char arr[SIZE];
    char name[SIZE];
    int num = 1;
    printf("파일 이름: ");
    gets(name);
    if ((fp=fopen(name,"r"))==NULL)
    {
        printf("파일 오픈 실패\n");
        exit(1);
    }
    while (!feof(fp))
    {
        fgets(arr, SIZE, fp); //fgets함수는 개행문자까지 받는다.
        if (arr[strlen(arr) - 1== '\n')
            {
                arr[strlen(arr) - 1= '\0';
            }  //따라서 개행문자가 출력되므로 개행문자를 NUL문자로 바꿔준다.
        printf("%6d: ", num); //폭6 오른쪽정렬
        puts(arr);
        num++;
    }
    fclose(fp);
    return 0;
}
cs





반응형
반응형

두 개의 텍스트 파일을 서로 비교하는 프로그램을 작성하여 보자. 파일의 이름은 사용자에게 입력받는다. 만약 두개의 파일이 일치하면 "파일은 서로 일치함"을 출력하며 일치하지 않으면 일치하지 않는 첫 번째 문장을 다음과 같이 출력한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
int main(void)
{
    FILE *fp1;
    FILE *fp2;
    char a[SIZE];
    char b[SIZE];
    char f1[SIZE];
    char f2[SIZE];
    int bytes=0;
    printf("첫번째 파일 이름: ");
    gets(a);
    printf("두번째 파일 이름: ");
    gets(b);
    if((fp1=fopen(a,"r"))==NULL)
    {
        fprintf(stderr,"파일 열기 오류1\n");
        exit(1);
    }
    if((fp2=fopen(b,"r"))==NULL)
    {
        fprintf(stderr,"파일 열기 오류2\n");
        exit(1);
    }
    while(1)
    {
    fgets(f1,sizeof(f1),fp1); //fgets는 \n(개행문자) 나올 때까지 문자열을 받음 
    fgets(f2,sizeof(f2),fp2);
    if(strcmp(f1,f2)!=0// f1이 크면 양, f2가 크면 음, 같으면 0
    {
        printf("<< %s\n", f1);
        printf(">> %s\n", f2);
        break;
    }
    if(feof(fp1)!=0// 파일의 끝이면 not0, 끝이 아니면 0
    {
    printf("파일은 서로 일치함\n");
    break;
    }
    }
    return 0;
}
cs

만약 일치하지 않는 모든 문장을 나타내고 싶으면 strcmp 가 들어간 if 문에서 break; 만 빼주면 될 것이다.




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C언어' 카테고리의 다른 글

인쇄 가능 문자 수 세기  (0) 2017.02.13
성적 평균 구하기  (0) 2017.02.12
fgets 함수  (0) 2017.02.11
파일 복사  (0) 2017.01.31
대문자로 변경  (0) 2017.01.31

+ Recent posts