如何解决如何使用 CPP 在文本文件中写入
实际上,我将带有值的四维数据放入文本文件“fourdimensionalM.txt”中,我想从具有
的txt文件“fourdimensionalM.txt”中读取数据0 0 0 2 1
0 0 2 0 2
0 1 0 0 3
0 1 1 1 4
0 1 2 0 5
并想将四维矩阵没有数字的地方写入新的txt文件。我编写代码,但这仅将零值保存到值位置五列,但我想将非零值写入 txt 文件“fourdimensionalM.txt”并将其保存在新的 txt 文件中。
#include <iostream>
#include<vector>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
int X=4,Y=4,Z=4,M=4;
/*printf("Enter size of 1st dimension X= ");
scanf("%d",&X);
printf("\n Enter size of 2nd dimension Y= ");
scanf("%d",&Y);
printf("\n Enter size of 3rd dimension Z= ");
scanf("%d",&Z);
printf("\n Enter size of 4th dimension M= ");
scanf("%d",&M);
printf("\n"); */
srand((unsigned) time(0));
ofstream fourDtensor;
fourDtensor.open("fourDtensor.txt");
ifstream four_dimension_tensor("uber3.txt");
int a,b,c,d,vl,new_x_1,new_x_2,flag;
cout<<"Starting"<<endl;
for (int i = 0; i < X; i++)
{
//cout<<i<<endl;
for (int j = 0; j < Y; j++)
{
for (int k = 0; k < Z; k++)
{
for(int l=0; l < M; L++)
{ flag=0;
cout<<"before"<<endl;
while(!four_dimension_tensor.eof()){
four_dimension_tensor>>a>>b>>c>>d>>vl;
cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<vl<<endl;
if(a==i && b==j && c==k && d==l){
flag=1;
}
}
cout<<"after"<<endl;
if(flag==1){
fourDtensor << i<< " " << j << " " << k << " "<< l << " " << vl ;
fourDtensor << endl;
}
else{
fourDtensor << i<< " " << j << " " << k << " "<< l << " " << 0 ;
fourDtensor << endl;
}
}
}
}
}
return 0;
}
解决方法
如果我正确理解您的问题,您将获得一个包含 R^4 选择点值的文件,您需要为没有点的地方生成带有零的完整超立方体。
如果您可以假设输入文件按字典顺序排序,您可以执行以下操作:
int ti,tj,tk,tl,tv; // target coordinates and value
ifstream targets("uber3.txt");
void advance() {
targets >> ti >> tj >> tk >> tl >> tv;
if (targets.eof()) {
ti = tj = tk = tk = -1;
}
}
int get_value(int i,int j,int k,int l) {
if (i == ti && j == tj && k == tk && l == tl) {
// the arguments match the current target
int ret = tv; // advance() overwrites tv,so take a copy
advance();
return ret;
} else {
return 0;
}
}
然后你的主循环的核心(即在四个嵌套的 for
循环内)变得简单:
fourDtensor << i << " " << j << " " << k << " " << l << " " << get_value(i,j,k,l);
不要忘记在程序开始时调用一次 advance()
!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。