자주 까먹는 c++ 문법

semi·2020년 9월 7일
0

etc

목록 보기
4/8

공백이 있는 문장의 입력을 받을 때

  • fgets 함수 사용하기
  char ch[101];
  fgets(ch, sizeof(ch) - 1, stdin);
문장의 마지막에 개행문자 \n이 포함되므로 사용시 제거하고 사용해야 한다.
string이 아닌 char 배열로 사이즈가 정해져있는 배열에 사용해야 한다.
  • getline 함수 사용하기
  string text;
  getline(cin, text);
위의 fgets와 달리 문장 내에 \n이 포함되지 않는다.

문자열에 포함된 부분문자열 찾기

  • find 함수 사용하기
  string str = "ABCDE";
  string origin = "AB";
  if (str.find(origin) != string::npos)
  {
      //str이 origin을 포함한 경우
  }

string 소문자화

  • tolower 함수 사용
#include <algorithm>
#include <string> 

using namespace std;

string data = "HELLO WORLD"; 
transform(data.begin(), data.end(), data.begin(), ::tolower);

char digit 여부 판별

  • isdigit 함수 사용
#include <string>

using namespace std;

string s = "", str = "abc1234";
for(int i = 0;i<str.size();i++)
{
	if (isdigit(str[i]))
	{
		s += str[i];
	}
}

auto 출력

  • 순방향
for (auto o = dq.begin(); o != dq.end(); o++)
{
	if (o == dq.end() - 1)
    {
    	cout << *o;
    }
    else
    {
    	cout << *o << ",";
    }
}
  • 역방향
for (auto o = dq.rbegin(); o != dq.rend(); o++)
{
	if (o == dq.rend() - 1)
    {
    	cout << *o;
    }
    else
    {
    	cout << *o << ",";
    }
}

struct 활용

#include <iostrea>
#include <queue>

using namespace std;

struct Point
{
	int y, x, p;
};

int main(void)
{
	queue<Point> q;
    q.push({1, 2, 3});
	return 0;
}

0개의 댓글