CPP 문자열 클래스 실습

실습과제 모음 2014. 4. 26. 12:07 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

문자열 검색 실습

주어진 문자열 "Hello World"에 있는 문자를 검색한다.

입력된 문자 x 가 주어진 문자열 내에 존재한다면

x 가 존재합니다.

입력된 문자 x 가 주어진 문자열 내에 존재하지 않는다면

x 가 존재하지 않습니다.

가 출력된다.


#include <stdio.h>

#include <iostream>

using namespace std;

int main( )

{

    string object = "Hello World";

    char searchChar;

    int exist = 0;

    cin >> searchChar;

 

    cout << object.at(0) << endl;

    cout << object.at(1) << endl;

    cout << object.at(2) << endl;

    // .......

 

    // exist

    // 1        존재O

    // 0        존재X

    if( exist )

    {

        cout << searchChar << "가존재합니다." << endl;

    }

    else

    {

        cout << searchChar << "가존재하지않습니다." << endl;

    }

    return 0;

}

 

'실습과제 모음' 카테고리의 다른 글

CPP 학생 관리 프로그램  (0) 2014.04.26
CPP 문자열 찾기 실습 답  (0) 2014.04.26
studentInfo 실습  (1) 2014.04.19
C 배열 연습문제  (0) 2014.04.13
C 언어 달력 소스코드  (0) 2014.04.05
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

아두이노 & CPP 연동


출처 : http://playground.arduino.cc/Interfacing/CPPWindows#.UxLbvuN_uSo




SerialClass.h

#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED

#define ARDUINO_WAIT_TIME 2000

#include 
#include 
#include 

class Serial
{
    private:
        //Serial comm handler
        HANDLE hSerial;
        //Connection status
        bool connected;
        //Get various information about the connection
        COMSTAT status;
        //Keep track of last error
        DWORD errors;

    public:
        //Initialize Serial communication with the given COM port
        Serial(char *portName);
        //Close the connection
        //NOTA: for some reason you can't connect again before exiting
        //the program and running it again
        ~Serial();
        //Read data in a buffer, if nbChar is greater than the
        //maximum number of bytes available, it will return only the
        //bytes available. The function return -1 when nothing could
        //be read, the number of bytes actually read.
        int ReadData(char *buffer, unsigned int nbChar);
        //Writes data from a buffer through the Serial connection
        //return true on success.
        bool WriteData(char *buffer, unsigned int nbChar);
        //Check if we are actually connected
        bool IsConnected();


};

#endif // SERIALCLASS_H_INCLUDED
SerialClass.cpp
#include "SerialClass.h"

Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFile(portName,
            GENERIC_READ ,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             //Set the parameters and check for their proper application
             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
             }
             else
             {
                 //If everything went fine we're connected
                 this->connected = true;
                 //We wait 2s as the arduino board will be reseting
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}

Serial::~Serial()
{
    //Check if we are connected before trying to disconnect
    if(this->connected)
    {
        //We're no longer connected
        this->connected = false;
        //Close the serial handler
        CloseHandle(this->hSerial);
    }
}

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}


bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);

        return false;
    }
    else
        return true;
}

bool Serial::IsConnected()
{
    //Simply return the connection status
    return this->connected;
}
main.cpp
#include 
#include 
#include "SerialClass.h"	// Library described above
#include 

// application reads from the specified serial port and reports the collected data
int main(int argc, _TCHAR* argv[])
{
	printf("Welcome to the serial test app!\n\n");

	Serial* SP = new Serial("\\\\.\\COM3");    // adjust as needed

	if (SP->IsConnected())
		printf("We're connected");

	char incomingData[256] = "";			// don't forget to pre-allocate memory
	//printf("%s\n",incomingData);
	int dataLength = 256;
	int readResult = 0;
	FILE *f;
	f = fopen("TempData.txt","w");

	while(SP->IsConnected())
	{
		readResult = SP->ReadData(incomingData,dataLength);
		//		printf("Bytes read: (-1 means no data available) %i\n",readResult);

		std::string test(incomingData);

		printf("%s",incomingData);

		char* token = strtok(incomingData, " ");
		while (token!=NULL) {
			fprintf(f,"\t%s",token);
			token = strtok(NULL, " ");
		}
		
		// strtok // token
		test = "";

		Sleep(1000);
	}
	fclose(f);
	return 0;
}

'Programming > C,CPP,CS' 카테고리의 다른 글

CString Convert 변환  (0) 2014.03.08
MFC 시리얼 통신 클래스  (0) 2014.03.08
아두이노 기본 세팅  (0) 2014.03.02
CPP 연산자 오버로딩  (0) 2014.01.16
CPP 연산자 오버로딩  (0) 2014.01.16

아스키코드표

Programming/C,CPP,CS 2013. 5. 2. 22:04 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

DEC Char DEC Char DEC Char
0 Ctrl-@ NUL 43 + 86 V
1 Ctrl-A SOH 44 , 87 W
2 Ctrl-B STX 45 - 88 X
3 Ctrl-C ETX 46 . 89 Y
4 Ctrl-D EOT 47 / 90 Z
5 Ctrl-E ENQ 48 0 91 [
6 Ctrl-F ACK 49 1 92 \
7 Ctrl-G BEL 50 2 93 ]
8 Ctrl-H BS 51 3 94 ^
9 Ctrl-I HT 52 4 95 _
10 Ctrl-J LF 53 5 96 `
11 Ctrl-K VT 54 6 97 a
12 Ctrl-L FF 55 7 98 b
13 Ctrl-M CR 56 8 99 c
14 Ctrl-N SO 57 9 100 d
15 Ctrl-O SI 58 : 101 e
16 Ctrl-P DLE 59 ; 102 f
17 Ctrl-Q DCI 60 < 103 g
18 Ctrl-R DC2 61 = 104 h
19 Ctrl-S DC3 62 > 105 i
20 Ctrl-T DC4 63 ? 106 j
21 Ctrl-U NAK 64 @ 107 k
22 Ctrl-V SYN 65 A 108 l
23 Ctrl-W ETB 66 B 109 m
24 Ctrl-X CAN 67 C 110 n
25 Ctrl-Y EM 68 D 111 o
26 Ctrl-Z SUB 69 E 112 p
27 Ctrl-[ ESC 70 F 113 q
28 Ctrl-\ FS 71 G 114 r
29 Ctrl-] GS 72 H 115 s
30 Ctrl-^ RS 73 I 116 t
31 Ctrl_ US 74 J 117 u
32 Space 75 K 118 v
33 ! 76 L 119 w
34 " 77 M 120 x
35 # 78 N 121 y
36 $ 79 O 122 z
37 % 80 P 123 {
38 & 81 Q 124 |
39 ' 82 R 125 }
40 ( 83 S 126 ~
41 ) 84 T 127 DEL
42 * 85 U  

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

#include <string>

using namespace std;

 

int main()

{

    string str;

    string tempStr[10];

    int tempStrSeq = 0;

    int tempStrCount[10] = {0};

    int start = 0, many = 0;

    getline(cin, str, '\n');

    for( int i = 0 ; i < str.length() ; i++ )

    {

        if( str.at(i) == ' ' || str.at(i) == ',' || str.at(i) == '.' )

        {

            if( many != 0)

            {

                cout << str.substr(start,many) << endl;

                int flag = 0;

                for( int j = 0 ; j < tempStrSeq + 1 ; j++ )

                {

                    if( tempStr[j].compare(str.substr(start,many)) == 0 )

                    {

                        flag++;

                        tempStrCount[j]++;

                    }

                    else

                    {

                        // 같지않다면

                    }

                }

                if( flag == 0)

                {

                    tempStr[tempStrSeq] = str.substr(start,many);

                    tempStrCount[tempStrSeq]++;

                    tempStrSeq++;

                }

                cout << "s : "<< start << "m : " << many << endl;

                many = 0;

            }

            start = i+1;

        }

        else

        {

            many++;

        }

    }

    if( many != 0)

    {

        cout << str.substr(start,many) << endl;

        int flag = 0;

        for( int j = 0 ; j < tempStrSeq + 1 ; j++ )

        {

           if( tempStr[j].compare(str.substr(start,many)) == 0 )

            {

                flag++;

                tempStrCount[j]++;

            }

            else

            {

                // 같지않다면

            }

        }

        if( flag == 0)

        {

            tempStr[tempStrSeq] = str.substr(start,many);

            tempStrSeq++;

            tempStrCount[tempStrSeq]++;

        }

        cout << "s : "<< start << "m : " << many << endl;

    }

 

    // TODO: 계산

 

    for( int i = 0 ; i < 10 ; i++ )

    {

        cout << tempStr[i] ;

        cout << " " << tempStrCount[i] << endl;

    }

}

'Programming > C,CPP,CS' 카테고리의 다른 글

아스키코드표  (0) 2013.05.02
프로그래밍용으로 좋은 폰트  (0) 2013.03.23
CPP string 줄단위 입력  (0) 2013.01.26
링크드리스트 학생관리  (0) 2013.01.19
C언어 달력소스코드  (0) 2013.01.13

CPP string 줄단위 입력

Programming/C,CPP,CS 2013. 1. 26. 15:48 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
CPP string 줄단위 입력


 string str;
 getline(cin, str, '\n');

 

 

CPP 표준체중 계산 프로그램

실습과제 모음 2012. 7. 26. 13:48 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

using namespace std;

class standardWeight

{

private:

   double  height, weight;

   int  WeightStatus;

public:

   void  setHeight(const double h);

   void  setWeight(const double w);

   double  getHeight();

   double  getWeight();

   int  StdWeight();

   int  getWeightStatus();

};

void  standardWeight::setHeight(const double h)

{

   height = h;

}

void  standardWeight::setWeight(const double w)

{

   weight = w;

}

double  standardWeight::getHeight()

{

   return height;

}

double  standardWeight::getWeight()

{

   return weight;

}

int  standardWeight::StdWeight()

{

   if(   (height - 100) * 0.9 < weight )

   {

       // 과체중

       WeightStatus = 1;

       return 1;

   }

   else if( (height - 100) * 0.9 > weight )

   {

       // 저체중

       WeightStatus = -1;

       return -1;

   }

   else

   {

       WeightStatus = 0;

       return 0;

   } 

}

int  standardWeight::getWeightStatus()

{

   return WeightStatus;

}

 

int main()

{

   standardWeight sw1;

   sw1.setHeight(170);

   sw1.setWeight(60);

   sw1.StdWeight();

   cout << sw1.getWeightStatus() << endl;

   return 0;

}

 

 

'실습과제 모음' 카테고리의 다른 글

CPP 주말 과제 Time 클래스  (0) 2012.07.27
CPP ImaginaryNumber  (0) 2012.07.27
CPP 함수 실습과제  (0) 2012.07.25
CPP 함수 cvr, cba, cbv  (0) 2012.07.24
CPP 실습과제 0724 배열, 함수  (0) 2012.07.24

CPP 달력 소스코드

Programming/C,CPP,CS 2012. 7. 21. 10:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>
using namespace std;


int main()
{
 int year;
 int month;
 int totalDay = 0;
 int i = 1990;
 int dayOfWeek; // 0 : 월, 1: 화, .....
 int dayOfMonth; // 해당 달의 총 일수

 cout << "년도 입력 : " ;
 cin >> year;
 cout << "월 입력 : " ;
 cin >> month;

 for( ; i < year ; i++)
 {
  if( i % 4 == 0 && i % 100 != 0 || i % 400 == 0 )
  {
   totalDay += 366;
  }
  else
  {
   totalDay += 365;
  }
 }

 cout << year << "년 1월 1일 까지의 일수 " << totalDay << "요일 : ";

 switch( totalDay % 7 )
 {
 case 0:
  cout << "월요일" << endl;
  break;
 case 1:
  cout << "화요일" << endl;
  break;
 case 2:
  cout << "수요일" << endl;
  break;
 case 3:
  cout << "목요일" << endl;
  break;
 case 4:
  cout << "금요일" << endl;
  break;
 case 5:
  cout << "토요일" << endl;
  break;
 case 6:
  cout << "일요일" << endl;
  break;
 }

 for( i = 1; i < month ; i++ ) // 5
 {
  // 1 + 2 + 3 + 4
  switch(i)
  {
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
   totalDay += 31;
   break;
  case 4:
  case 6:
  case 9:
  case 11:
   totalDay += 30;
   break;
  case 2:
   if( (year % 4) == 0 && ( (year % 100) != 0 || (year % 400) == 0 ) )
   {
    totalDay += 29;
   }
   else
   {
    totalDay += 28;
   }
   break;
  }
 }

 cout << year << "년 "<< month<<"월 1일 까지의 일수 " << totalDay << "요일 : ";

 switch( totalDay % 7 )
 {
 case 0:
  cout << "월요일" << endl;
  break;
 case 1:
  cout << "화요일" << endl;
  break;
 case 2:
  cout << "수요일" << endl;
  break;
 case 3:
  cout << "목요일" << endl;
  break;
 case 4:
  cout << "금요일" << endl;
  break;
 case 5:
  cout << "토요일" << endl;
  break;
 case 6:
  cout << "일요일" << endl;
  break;
 } 


 switch(month)
 {
 case 1:
 case 3:
 case 5:
 case 7:
 case 8:
 case 10:
 case 12:
  dayOfMonth = 31;
  break;
 case 4:
 case 6:
 case 9:
 case 11:
  dayOfMonth = 30;
  break;
 case 2:
  if( (year % 4) == 0 && ( (year % 100) != 0 || (year % 400) == 0 ) )
  {
   dayOfMonth = 29;
  }
  else
  {
   dayOfMonth = 28;
  }
  break;
 }

 cout << year << "년 " << month << "월 달력 =====" << endl;
 cout << "월 화 수 목 금 토 일" << endl;
 cout << dayOfMonth << "일 입니다" << endl;

 

 for( i = 0 ; i < totalDay % 7 ; i++)
 {
  cout << "   " ;
 }
 for(i = 1; i <= dayOfMonth ; i ++ )
 {  
  printf("%2d ", i);

  if( totalDay % 7 == 6)
  {
   cout << endl;
  }
  totalDay++;  
 }


 cout << endl << endl;


 return 0;
}

 

'Programming > C,CPP,CS' 카테고리의 다른 글

프로그래밍 경진대회 관련 사이트  (0) 2012.10.14
CPP 예외처리  (0) 2012.09.23
C언어 정렬 알고리즘 예제  (0) 2012.08.26
C 달력 소스코드  (2) 2012.07.23
정렬 알고리즘 정리  (0) 2012.07.20