코딩/C++

[C++] .txt 등 파일 열기, 랜덤 값 생성 코드

peter_00 2024. 7. 17. 14:06
반응형

텍스트 파일 열기

 

#include <fstream>
using namespace std;

int main()
{
    ifstream inData; 		       //declare an input file stream
    ofstream outData;		       //declare an output file stream
    string firstName, lastName;

    inData.open("names.txt"); 	 // open input file
    outData.open("marks.txt");       // open output file
    
    inData >> firstName >> lastName;  // read from a file stream
    outData << 85.6;		         // write into a file stream

    inData.close();  	 	        // close the input file
    outData.close();      	        // close the output file
    return 0;
}

inData.open (" 열고자 하는 파일 이름.txt " );

outData.open (" 새로 저장할 파일 이름.txt" );

 

inData 로 데이터를 읽어올 파일의 이름을 특정 했으니 어떠한 데이터를 읽을지 결정한다

inData >> firstName >> lastName; [성과 이름을 읽는다]

outData << 85.6; 문서에 85.6이라는 숫자를 적는다.

 

inData.close(); 

outData.close(); 두 파일 모두 항상 .close(); 를 해줘야 프로그램이 정상 종료된다.

 

#include <fstream>
using namespace std;

int main()
{
    ifstream inData; 	// declare an input file stream
    char fileName[] = "exams.txt";
    string lastName, mark;

    inData.open( fileName ); 	 // open input file
    if (!inData)  		// check if opened successfully
    {
      cerr << "Error opening : " << filename << endl;
      return -1; 		// exit with an error code
    }
    inData >> lastName >> mark;

    inData.close();  	// Close the input file
    return 0;
}

If 문을 활용하여 특정 파일이 열였는지 안열였는지 확인 가능하다.

 

ifstrean inData; input 파일 시스템을 사용 할거기 때문에 항상 선언을 해야한다.

char fileName[] = "exams.txt" 파일 이름을 특정해준다.

string lastName. mark; 

 

inData.open ( fileName ); input 파일을 열게하는 코드이다.

if (!inData) if문을 활용하여서 앞서 설정했던 파일의 이름과 동일한 파일이 없다면 return -1; 을 결과값으로 나타낸다 -1 은 false 값이기 때문에 종료된다.

 

inData >> lastName >> mark; 파일이 정상적으로 열렸다면 파일의 lastName 항목에 mark를 적는다.

 

inData.close(); close를 해야 파일이 안전하게 저장되고 프로그램이 정상 종료된다.

 

4가지의 에러체크 기능이 있다

 

1. eof = end of file 파일의 끝

if( inData.eof() )  {  Error recovery action }

2. fail = 잘못된 데이터로 인하여 종료

if( inData.fail() ) {  Error recovery action }

3. bad = 하드웨어 문제

if( inData.bad() ) {  Error recovery action }

4. function good() 의 값이 true를 나타내는 경우는 아무런 에러가 감지되지 않았을 때 이다.

 

nA text file has content:

 1 2 3

nAssuming appropriate headers etc 

 while( ! inData.eof() )

   { 

       inData >> number;

       cout << number << " ";

   }

nProduces output …

1 2 3 3

 

텍스트 파일의 컨텐츠는 1 2 3 이라고 가정해ㅐ보자

eof의 가 false 이면 inData는 넘버를 읽는다

cout 으로 인하여 number에 "1"이라는 값이 추가되고 << 를 따라서 빈칸인 " "; 를 나타낸다.

그래서 output은

1 " " 2 " " 3 " " 3

하지만 마지막 3까지 읽었다면 eof 가 발동된다. 

 

inFile >> newNumber;

if( inFile.fail() )

{

    inFile.clear();

    inFile.ignore(100, ‘\n’);

}

 

inFile.clear(); 를 이용하여 에러가 발생했을때 복구 하는 기준을 정한다.

 

int readData(ifstream& inFile, InfoType& student, string myId)

// inFile 은 파일을 읽기위함 student 는 정보 타임 myId는 c++ 오브젝트이다

{ 

   string nameFirst;

   string nameLast;

   string Id;

        

   do inFile >> nameFirst >> nameLast >> Id;

// nameFirst 를 읽고 nameLast 를 읽고 마지막으로 Id를 읽는다

 

   while( inFile.good() && Id != myId );

// inFile.good() 이고  Id 가 myId 와 동일하지 않다면

 

   if(inFile.fail())  return -1;         // invalid character

   if(inFile.bad())   return -2;         // hardware failure

   if(inFile.eof() && Id=="") return -3; // myId not found

 

   student.firstName = name.First;

   student.lastName = name.Last;

   student.Id = Id;

   return 0;

}

 

데이터에 빈칸이 존재 할 때

예시)

float price;

char productName[20] ;

char fileName[] = "test.txt";

ifstream inData;

 

inData.open( fileName );

inData >> price; // 가격을 불러오고

 

inData.getline(productName, 20); //제품 이름을 불러와야 함

하지만 text.txt 에서 34.99를 읽고 난 후에 빈칸이 존해하기 때문에 Motor Oil로 가지 못함

cout << price << endl; //34.99

cout << productName << endl; // " " 이렇게 빈칸을 불러오게됌

 

이러한 문제를 해결하기 위해서 inData.ignore 을 사용 해야함

So, we need to clear the buffer … 이러한 버퍼 문제를 해결하기 위해서 ...

inData >> price;

inData.ignore( 20, ‘\n’ ); // 이렇게 '/n'을 이용하여 빈칸 버퍼 문제를 해결

inData.getline(productName, 20);

 

프로그램이 빠르게 실행되기 위해서는 버퍼 문제를 잡아야함

 

#로 시작을 하면 끝에 ; 를 안붙여도 됌

Directives:
Source file inclusion: #include
Macro definition/replacement: #define
Conditional compilation: #ifndef, #ifdef, #else, #endif…
 

SALES_DATA_H 가 if not defined (ifndef) 라면 #define SALES_DATA_H 를 실행한다.

 

struct 사용법 

struct AddressType 
{ 
	string city; 
	int zip; 
}; 

struct StudentType 
{ 
	int id; 
	bool isGrad; 
	AddressType addr; 
};

Nested structure를 이용하려면 이런식으로 하면 된다

StudentType s; 
s.addr.zip = 53706; 

 

StydentType 안에 AddressType 이 있다 AddressType 을 addr로 지정했으니

AddressType 안에 있는 int zip 에 접촉할 수 있는 것이다.

 

c++에 랜덤을 이용하기

라이브러리에

$ CC -std=c++11 rand-eng.cpp 를 추가하고

 

(-std=c++11 은 라이브러리를 사용하기 위함이다)

#include <random>  ( 랜덤 기능을 사용하기 위해서 상단에 추가해야한다)

default_random_engine randEng;
for ( int i = 0; i < 10; i++)
  cout << randEng() << endl;

를 이용하면 된다 가장 기본이 되는 랜덤을 사용하는 코드이다.

 

Atoi 사용법

atoi 는 주로 인티저로 바꾸기 위해 사용된다

#include<iostream>
#include<string> 
#include<sstream>
using namespace std;

string itos(int i) // int를 string 으로 변환하기
{
	stringstream s;
	s << i;
	return s.str();
}

int main()
{
	int i = 127;
	string ss = itos(i);
	const char* p = ss.c_str();
	cout << ss << " " << p << "\n";
}

Tokenization 코드

#include <vector>
#include <string>

vector<string> splitString (string str, string delim)
{
	vector <string> result;
    size_t pos = 0;
    string token;
    
    while ( (pose=str.find(delim)) != std::npos )
    {
    	token = str.substr (0, pos);
        result.push_back (token);
        str.erase (0, post+delim.length());
       
    }
    
    if (!str.empty())
    	result.push_back (str);
        
    return (result);
    
 }
 
 
 int main ()
 {
 	string s = "John, Doe, Clementi Rd, C++, 3.55";
    
    vector<string> dataItems = splitString (s, ", ");
    
    for (size_t i = 0; i<dataItems.size(); i++)
    	cout << dataItems [i] << endl;
        
 }

makefile 이란 ?

fa.cpp 는 fa.h 에 의지

fb.cpp 는 fb.h 에 의지

main.cpp 는 fa.h와 fb.h에 의지

3개의 파일을 다 합치는 prog 파일 생성

prog:  main.o fa.o fb.o
		g++ -o prog main.o fa.o fb.o
        
main.o: main.cpp fa.h fb.h
		g++ -c main.cpp
        
fa.o: fa.cpp fa.h
		g++ -c fa.cpp
        
fb.o: fb.cpp fb.h
		g++ -c fb.cpp

union 과 struct 의 차이

struct adt
{
    int i;
    float f;
};

union mytype
{
    int i;
    float f;
};
cout << sizeof(int) << " " << sizeof(float) << endl;

위 코드 실행 시 값은 4 4 가 나온다 왜냐하면 int 의 사이즈는 4 바이트 이고 float의 사이즈도 4  바이트 이기 때문이다

cout << sizeof(adt) << endl;

위 코드 실행 시 값은 8이 나온다 왜냐하면 struct 는 값의 바이트를 합치기 때문 (4+4)

cout << sizeof(mytype) << endl;

위 코드 실행 시 값은 4 가 나온다 왜냐하면 union 은 i 와 f 가 같은 메모리를 공유하기 때문에 두 값을 겹친다

 

 

반응형

'코딩 > C++' 카테고리의 다른 글

[C++] Struct, Union 이해하기  (0) 2025.01.21
[c++] template 사용하기  (0) 2024.08.22
[c++] using namespace 사용하기  (0) 2024.08.19
[Linux] Ubuntu Compile 컴파일 하는 법 + 파일 실행 법  (0) 2024.07.10
C++ 입문  (0) 2024.07.03