본문 바로가기

Programming/C++ 1

[C++] Chapter 2. Elementary Programming

반응형
  • Reading Input from the keyboard
    • use cin
#include <iostream>
using namespace std;

int main()
{
	cout << "Width: ";
	int Width;
	cin >> Width;
	cout << "Height:";
	int Height;
	cin >> Height;
	int area = Width * Height;
	cout << " Area " << area << "\n";
}
  • cin
  • cout
  • >>
  • <<

Key Input to Buffer Stream of cin

  • string, and char array
char int double float *
1byte 4byte 8byte 4bye 4byte
  • sizeof / strlen
    • sizeof is byte size [sizeof is operator]
    • strlen is length [strlen is function]

-> string literal should have "\n"

 

  • Password check [cin]
#include <iostream>
using namespace std;

int main()
{
	cout << "name : ";
	char name[20];
	cin >> name;
	cout << "your name is : " << name << endl;

	char pwd[100];
	cout << "enter your password: " << endl;
	while (true)
	{
		cout << "password : ";
		cin >> pwd;
		if (strcmp(pwd, "C++") == 0)
		{
			cout << "Password is correct program exit" << endl;

			break;
		}
		else
		{
			cout << "wrong password" << endl;

		}

	}

	return 0;
}

-> string literal comparsion check fucntion : strcmp [문자열 비교함수 : strcmp ( A, B )]

  • Line by Line input
    • not cin is no space input
    • getline
  • getline funciton
    • Reading a string with space in it [Read a line by line]
    • cin.getline(char buf[], int size, char delimitChar)
      • when encountering delimitChar, input stops
#include <iostream>
using namespace std;

int main()
{
	cout << "name : ";
	char name[20];
	cin.getline(name, 20,'\n');
	cout << "your name is : " << name << endl;
	

	char pwd[100];
	cout << "enter your password: " << endl;
	while (true)
	{
		cout << "password : ";
		cin.getline(pwd, 100);

		if (strcmp(pwd, "C ++") == 0)
		{
			cout << "Password is correct program exit" << endl;

			break;
		}
		else if(strcmp(pwd, "\0" )==0) // enter key 
		{
			cout << "program exit" << endl;
			break;
		}
		else
		{
			cout << "wrong password" << endl;

		}

	}

	return 0;
}

  • Named Constants
const datatype CONSTANTNAME = VALUE;

const double PI = 3.141592;
const int SIZE = 3;
반응형