如何初始化整数+字符串数组

How to Initialize Integers + String Arrays

本文关键字:字符串 数组 整数 初始化      更新时间:2023-10-16

我是C++新手,需要帮助!我目前正在学习如何制作2D阵列或1D阵列。

我有一个文本文件,下面显示了以下内容,我基本上是在尝试将它们存储到一个数组中,或者更多,具体取决于?如果我使用Struct,我真的只能有1个数组,或者根据下面文件中的内容有5个单独的数组吗?

我相信[1,2]可以形成一个2D阵列,但我该如何实现它呢?

下面是我使用结构的代码,我不确定我做得对不对?

请帮忙!

=========================================================
Sample Contents in 'HelloWorld.txt' File
=========================================================
[1, 2]-3-4-Hello_World
[5, 6]-7-8-World_Hello
[9, 1]-2-3-Welcome_Back
[4, 5]-6-7-World_Bye
[8, 9]-1-2-Bye_World
=========================================================
My Sample Codes
=========================================================
struct Example()
{
fstream file;
file.open("HelloWorld.txt");
vector<string> abc; 
string line;
while(getline(file, line, '-'))
{
abc.push_back(line);
int** a = new int*[abc.size()];
for(int i = 0; i < abc.size(); i++)
cout << abc[i] << endl;
delete [] a;
}
}

我的主要目标是能够将所有4个整数+1个字符串存储到数组中,并学习如何创建一个带有"[1,2]->前两个整定点的2D数组。

等待建议!非常感谢。

首先,使用c++特性和数据结构。您可以使用矢量而不是数组,这样更安全、更易于使用。其次,你们不必使用二维数组,你们可以使用一维数组,也就是矢量。我们的数据结构是你的结构向量的向量,你可以读取文件,用这些值创建一个结构,然后放在向量中。

#include <fstream>
#include <string>
#include <vector>
struct MyData
{
MyData():
num1(0),
num2(0),
num3(0),
num4(0),
str("")
{ }
int num1;
int num2;
int num3;
int num4;
std::string str;
};

void ReadFile(std::vector<MyData>& myVec)
{
std::string fileName = "HelloWorld.txt";
std::ifstream file(fileName, std::ios::binary);
if (file.fail())
{
std::cout << "Error while reading";
perror(fileName.c_str());
}
std::string line;
while (std::getline(file, line))
{
//parse this line
// store suitable values to the struct
// MyData myStruct;
// myStruct.num1 = ...
// myStruct.num2 = ...
// myStruct.num3 = ...
// myStruct.num4 = ...
// myStruct.str = ...
//myVec.push_back(myStruct);
// or you can directly use emplace_back that is more efficent
// but is more complicated for you now..
// you can practice...
}
}
int main()
{
std::vector<MyData> myVector;
ReadFile(myVector);
return 0;
}