C++ 为什么结果不会写入文本文件?
我已经创建了csis.txt文件,但当我查找时,它是空的。有人能告诉我为什么创建的文件没有结果吗?这是我的密码:C++ 为什么结果不会写入文本文件?,c++,file,text,extern,ofstream,C++,File,Text,Extern,Ofstream,我已经创建了csis.txt文件,但当我查找时,它是空的。有人能告诉我为什么创建的文件没有结果吗?这是我的密码: //ZipCode.cpp #include <iostream> #include "ZipCode.h" #include <fstream> #include <string> #include <math.h> #include <sstream> using namespace std; extern of
//ZipCode.cpp
#include <iostream>
#include "ZipCode.h"
#include <fstream>
#include <string>
#include <math.h>
#include <sstream>
using namespace std;
extern ofstream csis;
ZipCode::ZipCode(int _zipcode) {
zipcode = _zipcode;
}
ZipCode::ZipCode(const char *barcode) {
int value;
zipcode = 0;
for (int i = 0; i<5; i++) //repeat x5 positions
{
value = 0;
for (int j = 0;j<5;j++) //repeat x5 letters
{
if (barcode[i * 5 + j] == '1') //if '1' is letter
{
value += base[j]; //add position(5)
}
}
if (value >10)
{
value = 0;
}
zipcode = zipcode * 10 + value;
}
}
string ZipCode::getBarCode()
{
char barcode[26] = "";
int zip = zipcode;
int value;
for (int i = 0;i<5;i++) //repeat x5 positions
{
for (int j = 0;j<4;j++) //repeat x4(last barcode position 0)
{
//10^position * barcode position goes to value
value = (int)(pow(10.0, 4 - i) * base[j]);
if (zip / value)
{
barcode[i * 5 + j] = '1'; //set as '1'
zip = zip % value;//zip is now remainder
}
else
{
barcode[i * 5 + j] = '0'; //set as '0'
}
}
barcode[i * 5 + 4] = '0';
}
return barcode;
}
int ZipCode::getZipCode()
{
return zipcode;
}
//ZipCode.h
#ifndef _ZIPCODE_H
#define _ZIPCODE_H
using namespace std;
class ZipCode {
private:
int zipcode;
int base[5] = { 7,4,2,1,0 }; //barcode positions
public:
ZipCode(int _zipcode); //convert zipcode to barcode
ZipCode(const char *barcode); //convert barcode to zipcode
string getBarCode(); //get barcode
int getZipCode(); //get zipcode
};
#endif
//main.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include "ZipCode.h"
#include <sstream>
using namespace std;
ofstream csis;
int main()
{
csis.open("csis.txt");
ZipCode zip1(99504);
ZipCode zip2(12345);
ZipCode zip3(67890);
ZipCode zip4("100101010011100001100110001");
ZipCode zip5("110100001011100001100010011");
ZipCode zip6("100011000110101000011100101");
cout << "Digits" << " " << "Bar Code" << endl;
cout << zip1.getZipCode() << setw(35) << zip1.getBarCode() << endl;
cout << zip2.getZipCode() << setw(35) << zip2.getBarCode() << endl;
cout << zip3.getZipCode() << setw(35) << zip3.getBarCode() << endl;
cout << endl;
cout << zip4.getZipCode() << setw(35) << zip4.getBarCode() << endl;
cout << zip5.getZipCode() << setw(35) << zip5.getBarCode() << endl;
cout << zip6.getZipCode() << setw(35) << zip6.getBarCode() << endl;
return 0;
}
您可能希望编写该文件,而不是std::cout 只需替换:
cout << "Digits" << " " << "Bar Code" << endl;
借
对每一行重复一遍…但是你没有在任何地方写入文件吗?哦,天哪,我觉得好傻……谢谢!
csis << "Digits" << " " << "Bar Code" << endl;`