infile에서 숫자를 outfile에 사용하려면 어떻게해야합니까?C++에서 outfile에 숫자를 읽는 방법
예를 들어, 내가 infile에서 숫자를 읽고 outfile에 학생 ID로 표시하기 위해 그 숫자를 사용한다고 가정 해보십시오.
infile에서 숫자를 outfile에 사용하려면 어떻게해야합니까?C++에서 outfile에 숫자를 읽는 방법
예를 들어, 내가 infile에서 숫자를 읽고 outfile에 학생 ID로 표시하기 위해 그 숫자를 사용한다고 가정 해보십시오.
값을 작성하는 방법에 따라 약간 다릅니다.
분명히 파일을 열어야합니다.
outfile << data
으로 데이터를 기록한 경우 infile >> data
으로 읽을 수 있습니다.
fprintf()
을 사용한 경우 반드시 그렇지는 않지만 fscanf()
으로 읽는 것이 좋습니다.
시작하려면 outfile을 작성하기 위해 수행 한 작업을 Google에 표시하고 읽는 방법에 대한 간단한 시도를 해보십시오. 그런 다음 진행 방법에 대한 몇 가지 지침을 제공 할 수 있습니다.
행운을 빌어 요!
업데이트
상당히 분실 된 것처럼 보입니다. 내가 필요한 것들을 수행하는 짧은 프로그램을 작성했지만 코드를 읽을 필요가 있으므로 주석을 포함시키지 않았다. 당신이 필요한 것을 알아낼 수 있는지 살펴보십시오.
#include <iostream>
#include <fstream>
#include <string>
bool WriteNums(const std::string &sFileName, int nVal, double dVal)
{
std::ofstream ofstr(sFileName);
if (!ofstr.is_open())
{
std::cerr << "Open output file failed\n";
return false;
}
ofstr << nVal << " " << dVal;
if (ofstr.fail())
{
std::cerr << "Write to file failed\n";
return false;
}
return true;
}
bool ReadNums(const std::string &sFileName, int &nVal, double &dVal)
{
std::ifstream ifstr(sFileName);
if (!ifstr.is_open())
{
std::cerr << "Open input file failed\n";
return false;
}
ifstr >> nVal >> dVal;
if (ifstr.fail())
{
std::cerr << "Read from file failed\n";
return false;
}
return true;
}
int main()
{
const std::string sFileName("MyStyff.txt");
if(WriteNums(sFileName, 42, 1.23456))
{
int nVal(0);
double dVal(0.0);
if (ReadNums(sFileName, nVal, dVal))
{
std::cout << "I read back " << nVal << " and " << dVal << "\n";
}
}
return 0;
}
istream_iterator
및 ostream_iterator
꽤 재미 있습니다.
당신이 할 수있는 깔끔한 것들을 확인하십시오. 다음은 입력을 읽고 출력하는 화씨 - 섭씨 변환기의 간단한 예제입니다.
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
using namespace std;
typedef float input_type;
static const input_type factor = 5.0f/9.0f;
struct f_to_c : public unary_function<input_type, input_type>
{
input_type operator()(const input_type x) const
{ return (x - 32) * factor; }
};
int main(int argc, char* argv[])
{
// F to C
transform(
istream_iterator<input_type>(cin),
istream_iterator<input_type>(),
ostream_iterator<input_type>(cout, "\n"),
f_to_c()
);
return 0;
}
꽤 멋진 프로그램이지만, 초보자 (로버트처럼)가 많이 얻지는 않을지 확신하지 못합니다. –
@ 마이클 : 만약 그가 그것을 이해한다면, 그는 C를 쓰는 데 오랜 시간을 할애하고 C를 쓰지는 않을 것입니다. –
이 숙제입니까? –
숙제 인 경우 그것을 표시하십시오. – DanTheMan
이것은 기본적으로 그가 물었던 다른 질문과 관련이 있습니다. http://stackoverflow.com/questions/5652295/how-do-i-do-this-c-program –