gpt4 book ai didi

c++ - 将文件中的数字放入数组中

转载 作者:行者123 更新时间:2023-11-28 03:28:03 25 4
gpt4 key购买 nike

我有带数字的文件。

3
2 15 41
4 1 2 3 4
3 22 11 24

第一行显示其他行的存在方式(最多 100)。行中的数字不能超过 50。

需要将行中的数字放入数组中,例如:

line[lineNum][num]

我是 C++ 的新手,我要求以最简单的方式执行此操作。我尝试这样做:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
int kiek;
string str[100][50];
string line;
int a = 0;
int b = 0;

ifstream failas("Duom1.txt");

if (failas.is_open())
{
while (failas)
{
if (a == 29)
{
a = 0;
b++;
}

getline(failas, str[a][b], ' ');

}

a++;
}

cout << str[0][0] << endl;
}

最佳答案

逐行读取文件,然后自己解析每一行。

if (failas.is_open())
{
// read first line
string num_lines;
std::getline(failas, num_lines);
// read lines
for (int i = 0; std::getline(failas, line); ++i)
{
// parse line and insert into array
std::istringstream is(line);
string number;
for (int j = 0; is >> number; ++j)
str[i][j] = number;
}
}

不过,更好的方法是使用 std::vector 而不是数组:

std::vector<std::vector<int> > all_nums;
...
// read first line
string num_lines;
std::getline(failas, num_lines);
// read lines
while (std::getline(failas, line)) {
// parse line and insert into vector
std::istringstream is(line);
int number;
std::vector<int> line_nums;
while (is >> number)
line_nums.push_back(number);

// add line to vector
all_nums.push_back(line_nums);
}

关于c++ - 将文件中的数字放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com