gpt4 book ai didi

c++ - fstream 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:23 25 4
gpt4 key购买 nike

我正在将 vector 数组写入 ofstream 文件,但是某些值没有被写入,即:

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main (){
char * hold = new char [100];
vector<double> fx(2049);
ifstream inputFile;
ofstream myFile;
inputFile.open("data.txt");
myFile.open("test.txt");
for (int c=0; c<2049; c++){
inputFile.getline(hold, 100);
fx[c] = atof(hold);
}
for (int c=0; c<2049; c++){
myFile << fx[c] << "\n";
}
}

在fx中,后半部分全部等于0。(fx[1024]到fx[2048]==0)。然而,在 test.txt 中,这些 0 值都不存在,应用回车。有什么想法吗?谢谢! (这些问题的格式是新手……如果有任何提示可以使这个问题更容易理解,我们将不胜感激。)

注意:我意识到这个程序相当多余。实际的程序有更多的功能,这只是一个工作不正常的地方。

最佳答案

试试这个

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>

#define MAX_FILE_LINES 2048


using namespace std;

//genarate random double number
double fRand()
{
double fMin = 100, fMax = 200;
double f = (double)rand();
return fMin + (f / (fMax - fMin));
}

//init file (if you need to create sample file with list of double numbers, you can use this function)
void fileInit(){
ofstream sourceFile;
sourceFile.open("D:\\source.txt");
if (sourceFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
sourceFile << fRand() << endl;
}
}
}


int main (){
string buffer;
vector<double> fx(MAX_FILE_LINES);
ifstream sourceFile;
ofstream destinationFile;
sourceFile.open("D:\\source.txt");
destinationFile.open("D:\\destination.txt");

//reading file lines to vector
int lineCount =0;
if (sourceFile.is_open())
{
while ( sourceFile.good() )
{
getline (sourceFile,buffer);
fx[lineCount] = atof(buffer.c_str());
lineCount++;
if (lineCount == (MAX_FILE_LINES-1)){
break;
}
}
sourceFile.close();
}

//write lines to new file
if (destinationFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
destinationFile << fx[i] << endl;
}
}
}

关于c++ - fstream 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15627384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com