如何初始化整数+字符串数组
How to Initialize Integers + String Arrays
我是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;
}
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组