我试图在c++中编写一个函数或子程序,该函数或子程序需要一个数组并将其打印到文本文件。我知道用FORTRAN很容易做到这一点。我还没有找到一个好的方法在c++中做到这一点。由于
无论您使用的是std::vector<float>
还是float[]
风格的数组,过程都是相似的。
#include <iostream> // std::cout
#include <iterator> // std::ostream_iterator
#include <vector> // std::vector
#include <algorithm> // std::copy
int main () {
std::vector<float> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10.f);
std::ostream_iterator<int> out_it (std::cout,", ");
std::copy ( myvector.begin(), myvector.end(), out_it );
return 0;
}
这可能对你有帮助
#include <iostream> // library that contain basic input/output functions
#include <fstream> // library that contains file input/output functions
using namespace std;
int main()
{
char array[] = {'H','e','l','l','o',' ','W','o','r','l','d','!',' '}; //array to write into file
ofstream fout("test.txt"); //opening an output stream for file test.txt
/*checking whether file could be opened or not. If file does not exist or don't have write permissions, file
stream could not be opened.*/
if(fout.is_open())
{
//file opened successfully so we are here
cout << "File Opened successfully!!!. Writing data from array to file" << endl;
for(int i = 0; array[i] != ' '; i++)
{
fout << array[i]; //writing ith character of array in the file
}
cout << "Array data successfully saved into the file test.txt" << endl;
}
else //file could not be opened
{
cout << "File could not be opened." << endl;
}
return 0;
}