我想写一个读取文本文件test.txt的c ++代码 并将conetent写入几个数组。 该文件看起来像:
[7,13,17]
[[0,1,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
[1,0,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0]]
我写的代码
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int parameter[10];
int physical[7][7];
const char* filename;
filename = "src/cplex_N7.txt";
ifstream f(filename, ios::in);
if (!f) {
cerr << "No such file: " << filename << endl;
throw(1);
}
f >> parameter >> physical ;
// cout content
return 0;
}
但我总是遇到错误和错误的输出,请你以最好的方式帮助你做这件事。我的意思是我可以在没有for循环或没有处理逗号和分割器的情况下读取文件。
答案 0 :(得分:0)
你不能以这种方式处理字符串。您似乎正在使用try / error方法学习c ++,这是学习编程语言的最糟糕方式。 我写了一个小样本,以您的格式读取一行数字:
string x = "1,0,1,0,1,0,1,0,1,0";
int array[10];
for(int i = 0; i < x.size(); i+=2)
array[i / 2] = x[i] - '0';
数字在偶数索引处,因此我们应该迭代字符串的偶数姿势。每个都是一个char,我们可以通过从'0'中减去它们来获得int值。