template <class T>
void savetext(T *a, char const *b) //writes to text file inside .sln however the text file is corrupt
{
ofstream fout(b, ios::out);
for (int i = 0; a[i] != '\0'; i++)
fout << a[i] << endl;
cout << "Text file successfully written to." << endl;
}
template <class T>
void gettext(T *a, char const *b) //this is where the error occurs: inside the text file it puts the right values along with piles of junk. Why is this?
{
ifstream fin(b, ios::in);
if (fin.is_open())
{
cout << "File opened. Now displaying .txt data..." << endl;
for (int i = 0; a[i]!= '\0'; i++)
{
fin >> a[i];
}
cout << "Data successfully read." << endl;
}
else
{
cout << "File could not be opened." << endl;
}
}
int main()
{
const int n1 = 5, n2 = 7, n3 = 6;
int a[n1], x, y, z;
float b[n2] = {};
char c[n3] = "";
//Begin writing files to text files which I name herein.
cout << "Writing data to text 3 text files." << endl;
savetext(a, "integer.txt");
savetext(b, "float.txt");
savetext(c, "string.txt");
cout << endl;
//Retrieve the text in the files and display them on console to prove that they work.
cout << "Now reading files, bitch!" << endl;
gettext(a, "integer.txt");
gettext(b, "float.txt");
gettext(c, "string.txt");
cout << endl;
return 0;
system("PAUSE");
}
안녕하세요. C++ 프로그램은 현재 3 개의 텍스트 파일에 데이터 (정수, 부동 소수점 및 문자)를 쓰고 있습니다. 그러나 텍스트 파일에 데이터를 쓸 때 데이터는 텍스트 파일 안에 있지만, 이해할 수없는 텍스트와 큰 숫자와 큰 음수가 있습니다. 결코 입력하지 않은 데이터입니다.텍스트 파일에 쓰여진 데이터가 부분적으로 손상되어 복구 할 수 없습니다.
이 결과로 텍스트 파일에서 정보를 검색 할 수 없으며 텍스트 파일의 정보를 표시 할 수 없습니다. 어떻게 문제를 해결할 수 있습니까? 고맙습니다.
정적 배열 대신 std :: vector를 사용하고 있습니까? ok입니까? 프로그램이 파일에서 다양한 바이트 수를 읽으면 동적으로 할당 된 컨테이너 (예 : std :: vector)가 고정 된 바이트 수만 보유 할 수있는 정적 배열보다 낫습니다. 파일 크기가 사용 가능한 메모리보다 클 수 있으므로 하드 디스크에서 파일을 읽는 동안 파일을 처리하는 것이 좋습니다. 이렇게하면 파일의 모든 데이터를 메모리에 동시에 저장하지 않아도됩니다. 또한 크로스 플랫폼을 사용하는 경우 엔디안 및 유니 코드 인코딩에 대해 생각해야합니다. –