ex) 입력 : 길이 7의 숫자 1234567를 한번에 입력해야되고,
이를 1 / 2 / 3 / 4 / 5 / 6 / 7 이렇게 따로 받아야 되는상황
int a[7];
for(int i=0;i<7;i++){ //7개의 수를 받겠다.
scanf("%1d",&a[i]); //한글자씩 받아서 a배열에 넣기
}
ex) 띄어쓰기 없이 12345 입력했을때 한글자씩 입력받는것
#include <iostream>
#include <string>
using namespace std;
int temp = 0;
int main() {
string a;
cin >> a;
for (int i = 0; i < a.size(); i++) {
temp += a[i] - '0';
}
return 0;
}
ex) 입력 : "abc de fg" 를 name에 한번에 저장하기
string name;
getline(cin,name);
char name[1000];
gets_s(name,1000);
-> 길이를 알면
1. scanf("%d %d", &a, &b);
2. cin >> s1 >> s2;
3. for(int i=0; i<N; i++){
cin >> a[i];
}
-> 길이를 아는데 사이즈가 크면 scanf로 못받을까?
input : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 100
for (int i = 0; i < 100; i++) {
scanf(" %d", &a);
}
위와 같이 scanf 안에 공백을 넣어준다 => 개행 문자를 무시해준다.
-> 길이를 모르면 (문자)
ex) a b c d 가 입력으로 들어왔을때 하나씩 입력이 들어갈 수 있게끔
공백문자를 기준으로 문자열을 자르고 넣기 (주석 참조)
#include <iostream>
#include <string>
using namespace std;
string str_arr[1000];
int str_cnt=0;
int main() {
//string 변수 a 선언
string a;
//띄어쓰기를 포함한 전체 입력을 받는다.
getline(cin, a);
//받은 입력을 C의 형식으로 char buffer에 넣어주기 위한 변수선언. new는 malloc과 같은 동적할당 수행
char* str_buff = new char[1000];
//받은 입력 string a를 str_buff에 넣어준다.
strcpy(str_buff, a.c_str());
//strtok이 포인터를 반환하기때문에 tok을 포인터로 선언. 띄어쓰기를 기준으로 나눈다.
char* tok = strtok(str_buff, " ");
//tok을 살피며 끝이 아니라면 계속 진행한다.
while (tok != nullptr) {
//str_arr에 값을 추가한다.
str_arr[str_cnt++] = string(tok);
//띄어쓰기를 기준으로 나누어 다음 문자를 tok에 저장한다.
tok = strtok(nullptr, " ");
}
for (int n = 0; n < str_cnt; n++) {
cout << str_arr[n] << endl;
}
return 0;
}
-> 길이를 모르면 (숫자)
ex) 1 2 0 3 이 입력으로 들어왔을 때 하나씩 입력이 들어갈 수 있게끔
#include <iostream>
#include <string>
using namespace std;
char str[40];
int num=0;
int list[100];
int cnt = 0, i;
int main() {
//gets_s 로 char입력을 받아 한글자씩 처리해주자.
gets_s(str, 40);
for (int i = 0; cnt < 40 && str[i]; i++) {
if (str[i] != ' ') {
//char에서 -'0' 하면 int형이 된다.
num = num * 10 + str[i] - '0';
}
else {
if (num > 0) {
list[cnt++] = num;
num = 0;
}
}
}
return 0;
}
#include<string> 으로 사용가능
string s1;
string s2;
s1="john";
s2="sam";
a = s1[0]; // j
b = s1[1]; // o
c = s1[2]; // h
d = s1[3]; // n
e = s1+s2; // johnsam
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
cin >> a[i][j];
}
}
계속 업데이트 예정이니 더 알고싶은 input의 방법이 있다면 댓글 남겨주세요~!
[Effective C++ 3판] Chapter 2. 생성자, 소멸자 및 대입 연산자 (항목 5~12) (0) | 2023.02.07 |
---|---|
[Effective C++ 3판] Chapter 1. C++에 왔으면 C++의 법을 따릅시다. (항목 1~4) (0) | 2023.02.07 |
Java와 C#의 차이점 (0) | 2022.03.18 |
[C++] MFC란 무엇인가? (0) | 2022.02.26 |
[C++] 메모리 동적 할당 (new, delete) (0) | 2022.02.26 |