[C++] str, char, file Input/Output + EOF
String Input & Output
- 공백이 포함된 문장 읽기 (cin 으로는 맨 앞 단어만 읽힐때)
// C++ <string>
string line;
getline(cin, line);
getline(cin, line, '.'); // with delimiter
// C <cstdio>
// 1. Obsolete Style
char input[MAX_SIZE] = ""; // #define MAX_SIZE 101
fgets(input, MAX_SIZE, stdin);
fputs(input, stdout);
// 2. scanf format 활용 (regex 아님!)
char S[200];
scanf("%[^\n]", S); // \n 이 나올때까지 읽어라
// format ref - https://en.cppreference.com/w/cpp/io/c/fscanf
* scanf() doens't support any C++ classes.
stackoverflow.com/questions/20165954/read-c-string-with-scanf
Read C++ string with scanf
As the title said, I'm curious if there is a way to read a C++ string with scanf. I know that I can read each char and insert it in the deserved string, but I'd want something like: string a; sca...
stackoverflow.com
- How to read '\n' (newline) itself?
string input 중 newline이 들어오면 특별한 처리를 해야할때
문제점 : cin은 whitespace 모두 무시함. cin.get (혹은 getchar) 으로 한글자씩 입력받으면 whitespace 입력받기 가능.
isspace(ch)로 공백 문자 체크, ch == '\n'로 newline인 경우만 따로 처리.
EOF (End-of-File) 처리
휴대폰 자판 문제 처럼, 끝난다는 표시를 하지 않는 인풋을 받아야 하는 경우
C++ EOF 처리 방법 ( 백준 10951 A+B - 4 )
백준 10951번 문제 - A+B - 4 ( https://www.acmicpc.net/problem/10951 )를 풀면서 알게 된 것 이 문제는 입력의 마지막 조건이 어떤건지를 알려주지 않아서 JAVA의 hasNext()와 같은 게 C++에서는 무엇인지 알..
takeknowledge.tistory.com
Character Input & Output
scanf
그냥 일반적인 scanf("%c", &var); 는 '\n' 도 읽어들이기 때문에, 약간의 처리를 해줘야함.
// 1. Ignores consecutive whitespace
scanf(" %c", &var);
// 2. scanf Format
scanf("%*[ \n\t]%c", &var); // * skips characters grouped in [ ]
getchar
캐릭터 '단 하나' 만 입력받음. 엔터칠때 개행문자는 버퍼에 남기기 때문에, 다시 getchar 해서 없애주든가 해야함
[ C ]getchar()의 함정
main() { int input_char=0; while(1) { printf("Input Character : "); input_char = getchar(); if((in...
blog.naver.com
File Input & Output
I/O for local PS environment : gooddaytocode.blogspot.com/2016/04/freopen.html
파일을 처음 열때 : fopen
닫을 때 : fclose
닫고 다시 열때 : freopen (인자로 받은 stream 자동 close 후 다시 염)
[출저 : modoocode.com/59]
★ fclose 해야만, write한 내용들 반영됨 + 메모리 누수 방지
* 여러 파일들 열기
(ex. stdin stream으로 input.txt 'r' 모드로 열고, output.txt를 'w'로 열어서 결과 기록하기)
https://mathbits.com/MathBits/CompSci/Files/MultipleFiles.htm
freopen("../input.txt", "r", stdin);
auto fp = fopen("../output.txt", "w");
fprintf(fp, "%d\n", result);
fflush(fp);
fclose(fp);
트러블슈팅
BOJ 14500 테트로노미노를 풀다가 500x500 데이터셋이 필요해서 짜봄.
근데, 이러니까 나중에 printf 호출하면 에러뜨면서 프로그램이 죽어버림.
Q. freopen 은 세번째 인자로 받은 stream을 닫은 다음에 다시 열어주는 것 아닌가?
→ ㅇㅇ. 근데 stdout은 닫았고, main에서 새로 연건 stdin이니까 에러나지
#include <random>
#include <cstdio>
void random_world_generator(int row, int col) {
freopen("input.txt", "w", stdout);
printf("%d %d\n", row, col);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(1, 100);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
printf("%d ", distrib(gen));
printf("\n");
}
fclose(stdout); // 추후 printf를 부를때 에러가 남.
}
int main() {
random_world_generator(500, 500);
freopen("input.txt", "r", stdin);
...
printf("%d", each_pt); // ERROR!
}
그래서 아래와 같이 freopen을 fopen으로 바꿈.
파일 입력을 fputs로 해야 한다는 점이 짜증.
특히 숫자를 string으로 바꾼 뒤, c-style char * 로 이중 변환 하는 부분은 개선이 필요함.
#include <random>
#include <cstdio>
void random_world_generator(int row, int col) {
auto fp = fopen("input.txt", "w");
fputs(to_string(row).c_str(), fp); fputs(" ", fp);
fputs(to_string(col).c_str(), fp); fputs("\n", fp);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(1, 100);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++){
fputs(to_string(distrib(gen)).c_str(), fp);
fputs(" ", fp);
}
fputs("\n", fp);
}
fclose(fp);
}
int main() {
random_world_generator(500, 500);
freopen("input.txt", "r", stdin);
...
printf("%d", each_pt); // Good!
}
fprintf 를 이용하면 stdout 건들이지 않고 formatted print 로 파일 입력이 가능!
[출저 : dojang.io/mod/page/view.php?id=607]
#include <random>
#include <cstdio>
void random_world_generator(int row, int col, int from, int to) {
auto fp = fopen("input.txt", "w");
fprintf(fp, "%d %d\n", row, col);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(from, to);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
fprintf(fp, "%d ", distrib(gen));
fprintf(fp, "\n");
}
fflush(fp);
fclose(fp);
}
* 일부 내용이 파일에 안적히는 경우가 있더라. fflush 해주니까 정상화 됬음.
'<언어> > [C++]' 카테고리의 다른 글
[C++] Type Conversion 정리 (0) | 2020.12.07 |
---|---|
[C++] sorting (0) | 2020.12.06 |
[C++] 2-D array (0) | 2020.09.13 |
[C++] random generator (0) | 2020.09.10 |
[C++] iterator (0) | 2020.09.05 |