写数组函数的 C++ 问题
C++ Problems with write array function
我正在尝试编写一个将数组 (2D) 写入文件的函数。这是下面的代码:
#ifndef WRITE_FUNCTIONS_H_
#define WRITE_FUNCTIONS_H_
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void write_array(string name, int rows, int columns, double **array){
ofstream output;
output.open(name, ios::out);
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
output<<array[r][c]<<",";
}
output<<endl;
}
output.close();
}
#endif
当我在这个程序中尝试 运行 时:
#include <string>
#include <iostream>
#include "write_functions.h"
using namespace std;
int main(){
double **array = new double*[10];
for(int i = 0; i < 10; i++){
array[i] = new double[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
array[i][j] = i + j;
}
}
string array_name="home/Plinth/Documents/Temp/array.txt";
write_array(array_name, 10, 10, array);
return(0);
}
它 运行 非常好,没有错误或警告,但没有创建文件。我是不是写错了什么?我是不是用错了方法?
您可能在一个意想不到的目录中写入。
尝试像 /home/...
那样完全指定路径(注意第一个 '/'),或者像 array.txt
.
那样将其写入本地文件
在处理文件流时,我更喜欢使用这个习惯用法来及早发现错误。
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
std::ifstream input("no_such_file.txt");
if (!input) {
std::cerr << "Unable to open file 'no_such_file.txt': " << std::strerror(errno) << std::endl;
return 1;
}
// The file opened successfully, so carry on
}
我正在尝试编写一个将数组 (2D) 写入文件的函数。这是下面的代码:
#ifndef WRITE_FUNCTIONS_H_
#define WRITE_FUNCTIONS_H_
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void write_array(string name, int rows, int columns, double **array){
ofstream output;
output.open(name, ios::out);
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
output<<array[r][c]<<",";
}
output<<endl;
}
output.close();
}
#endif
当我在这个程序中尝试 运行 时:
#include <string>
#include <iostream>
#include "write_functions.h"
using namespace std;
int main(){
double **array = new double*[10];
for(int i = 0; i < 10; i++){
array[i] = new double[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
array[i][j] = i + j;
}
}
string array_name="home/Plinth/Documents/Temp/array.txt";
write_array(array_name, 10, 10, array);
return(0);
}
它 运行 非常好,没有错误或警告,但没有创建文件。我是不是写错了什么?我是不是用错了方法?
您可能在一个意想不到的目录中写入。
尝试像 /home/...
那样完全指定路径(注意第一个 '/'),或者像 array.txt
.
在处理文件流时,我更喜欢使用这个习惯用法来及早发现错误。
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
std::ifstream input("no_such_file.txt");
if (!input) {
std::cerr << "Unable to open file 'no_such_file.txt': " << std::strerror(errno) << std::endl;
return 1;
}
// The file opened successfully, so carry on
}