[英]Problem storing a 2D array in a file and then loading it C++
So, I'm trying to save a 2D string array in a file and trying to load it up again like when i reopen my program it should automatically assign the last input values.所以,我试图将一个 2D 字符串数组保存在一个文件中,并尝试再次加载它,就像我重新打开程序时一样,它应该自动分配最后一个输入值。 I'm having some trouble and I hope someone can look at my problem and help me with it as I'm just a beginner in C++.我遇到了一些麻烦,我希望有人可以看看我的问题并帮助我解决它,因为我只是 C++ 的初学者。 Here is my code:这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
//String Array To Store These boxes [ ] as values.
string arr[4][4]={{"[ ]","[ ]","[ ]","[ ]"},{"[ ]","[ ]","[ ]","[ ]"},{"[ ]","[ ]","[ ]","[ ]"},{"[ ]","[ ]","[ ]","[ ]"}};
void Save();
void Load();
fstream fin;
main()
{
Load();
for(int i=0; i<4; ++i)
{
for(int j=0; j<4; ++j)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
cout<<"Enter Value for A4: ";
cin>>arr[0][3];
Save();
getchar();
for(int i=0; i<4; ++i)
{
for(int j=0; j<4; ++j)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
getchar();
}
// Function to Save New Value In A File
void Save()
{
fin.open("New.txt",fstream::out);
for(int i=0; i<4; ++i)
{
for(int j=0; j<4; ++j)
{
fin<<arr[i][j];
}
}
fin.close();
}
// Function To Load Saved Values From The File Into Array arr
void Load()
{
fin.open("New.txt",fstream::in);
for(int i=0; i<4; ++i)
{
for(int j=0; j<4; ++j)
{
fin>>arr[i][j];
}
}
}
So, it runs perfectly the first time as I know it's a working code:所以,它第一次完美运行,因为我知道它是一个工作代码:
But when I reopen the program it messes up the matrix:但是当我重新打开程序时,它弄乱了矩阵:
What I want to do is to store the values for array elements by asking user to input the it can only be [X] I have it figured it in another main program and then I want to load the values from a file when I reopen the program.我想要做的是通过要求用户输入它来存储数组元素的值它只能是 [X] 我已经在另一个主程序中计算它然后我想在重新打开时从文件中加载值程序。 I'm only asking input for arr[0][3] right now because I'm just trying to figure the main idea of loading up my array and I'm calling it A4 because of the first row and 4th column.我现在只要求输入 arr[0][3] ,因为我只是想弄清楚加载我的数组的主要思想,因为第一行和第四列,我将其称为 A4。
The operator>> eats whitespace (space, tab, newline).运算符>> 吃空格(空格、制表符、换行符)。 In order to distinguish 1 string from another in your file, you need to have appropriate delimiter.为了将文件中的 1 个字符串与另一个字符串区分开来,您需要有适当的分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.