C++에서 입력을 처리하기 위한 두 가지 주요 방식
scanf : 매개변수로 받는 형식을 지정해서 입력을 받음
cin: 개행문자(띄어쓰기, 엔터)직전까지 입력을 받음
만약 문장 끝까지 받고 싶다면 getline을 써서 개행문자(\n/0를 줄의 끝으로 인식하고 그 직전까지 입력을 받음
언어 | C 표준 라이브러리 | C++ 표준 라이브러리 |
속도 | 더 빠름 (I/O 동기화를 하지 않음) | 기본적으로 느림 (I/O 동기화됨) |
가독성 | 가독성이 낮음 | 가독성이 높음 |
형식 지정 | 포맷 문자열 필요 (%d, %f 등) | 자동으로 데이터 타입을 추론 |
유연성 | 정밀한 제어 가능 | 유연하고 간결한 사용 |
입력 검증 | 직접 포맷 제어 가능 | 기본적으로 예외를 처리하거나 종료 |
배열/문자열 입력 | 편리 (%s, gets, fgets 등) | 문자열 입력 시 더 안전 (std::string) |
동작 방식 | 버퍼를 직접 처리 | 스트림 기반 (입출력 객체) |
에러 처리 | 반환값으로 성공 여부 확인 가능 | 기본적으로 예외 처리 방식 사용 |
#include <cstdio>
int main() {
int a;
float b;
char name[50];
// 입력
printf("Enter an integer, a float, and a string:\n");
scanf("%d %f %s", &a, &b, name);
// 출력
printf("Integer: %d, Float: %.2f, String: %s\n", a, b, name);
return 0;
}
#include <iostream>
#include <string>
int main() {
int a;
float b;
std::string name;
// 입력
std::cout << "Enter an integer, a float, and a string:\n";
std::cin >> a >> b >> name;
// 출력
std::cout << "Integer: " << a << ", Float: " << b << ", String: " << name << std::endl;
return 0;
}
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
#include <iostream>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int n, sum = 0;
for (int i = 0; i < 5; i++) {
std::cin >> n;
sum += n;
}
std::cout << "Sum: " << sum << "\n";
return 0;
}
std::getline(istream& is, std::string& str);
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "Enter a line of text:\n";
getline(cin, line); // 한 줄 입력
cout << "You entered: " << line << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "Enter multiple lines (type 'exit' to quit):\n";
while (true) {
getline(cin, line); // 한 줄 입력
if (line == "exit") break; // 'exit' 입력 시 종료
cout << "You entered: " << line << endl;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
cout << "Enter a line (comma will stop the input):\n";
getline(cin, line, ','); // ','를 기준으로 입력 종료
cout << "You entered: " << line << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
string name;
cout << "Enter your age: ";
cin >> age; // 숫자 입력 (개행 문자가 남음)
cout << "Enter your name: ";
getline(cin, name); // 개행 문자를 읽어 빈 입력 처리됨
cout << "Age: " << age << ", Name: " << name << endl;
return 0;
}
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main() {
int age;
string name;
cout << "Enter your age: ";
cin >> age;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 버퍼 정리
cout << "Enter your name: ";
getline(cin, name);
cout << "Age: " << age << ", Name: " << name << endl;
return 0;
}
typedef & using (0) | 2024.12.13 |
---|