공부해요/C
[ c++ 더쉽게,더깊게 ] ch3 . 변수로 사용자와 소통하기 ~p59
예쁜꽃이피었으면
2014. 8. 21. 00:58
변수 선언
type <변수명>;
ex) int A;
char letter;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //readnum.cpp #include <iostream> using namespace std; int main(){ int thisisanumber; //정수타입의 변수 선언 cout << "Please enter a number:"; cin >> thisisanumber; //사용자가 입력한 값을 thisisanumber변수에 저장 //사용자는 값입력 후 엔터를 눌러야 한다. cout << "You entered:" << thisisanumber << "\n"; } |
* 삽입 연산자
<<(씨아웃) - 출력할 때
>>(씨인) - 입력할 때
* cin.ignore();
- 문자 하나를 읽고 그 다음 문자를 무시한다.
* 변수의 연산
x += 5;
x -= 5;
x *= 5;
x /= 5;
++x;
x++;
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 | //calculator.cpp #include <iostream> using namespace std; int main(){ int first_argument; int second_argument; cout << "Enter first argument:"; cin >> first_argument; cout << "Enter second argument:"; cin >> second_argument; cout << first_argument << "*" << second_argument << "=" << first_argument * second_argument << endl; cout << first_argument << "+" << second_argument << "=" << first_argument + second_argument << endl; cout << first_argument << "/" << second_argument << "=" << first_argument / second_argument << endl; cout << first_argument << "-" << second_argument << "=" << first_argument - second_argument << endl; } |
* error : 'x' was not declared in this scope
선언되지 않은 변수를 사용하려고 했다.
* 변수선언
-변수의 초기화 필요
- 대소문자 구별
-의미있는 변수명 사용
* 문자열 string사용을 위해서는 <string>헤더의 선언이 필요하다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //string_name.cpp #include <iostream> #include <string> using namespace std; int main(){ string user_name; cout << "Plases enter your name:"; cin >> user_name; cout << "Hi" << user_name << "\n"; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //string_append.cpp //문자열 + 문자열 #include <iostream> #include <string> using namespace std; int main(){ string user_first_name; string user_last_name; cout << "Please enter your first name :"; cin >> user_first_name; cout << "Please enter your last name :"; cin >> user_last_name; string user_full_name = user_first_name + " "+ user_last_name; cout << "Your name is:" << user_full_name << "\n"; } |
* 문자열을 읽어 들일 때는 한 행 전체를 읽기도 한다.
getline()함수를 사용하면된다.
getline(cin , user_first_name,'\n');
특정 문자가 나올 때 까지 사용자 입력을 읽을 때도 유용핟.
반응형