[英]getline with ints C++
我有一个档案
0 3 2
1 2 3
4 5 6
6 8 1
每行的第一个数字是行,第二个数字是列,第三个数字是该行,列中包含的数据。 这将是给定的[8] [8]数组,因此我已经将所有内容初始化为0,但是如何存储每个数据值? 例如,我想要[0] [3] = 2和[1] [2] =3。我想跟踪发现行,col和数据值的那一行。 那么,如何正确地将这些值插入二维数组?
int rowcol[8][8];
for (int i=0; i < 9; i++)
for (int j=0; j < 9; j++)
{
rowcol[i][j] =0;
}
ifstream myfile;
int nums;
myfile.open(text.c_str());
while (!myfile.eof()) {
myfile >> nums;
numbers.push_back(nums);
}
for (int i=0; i < numbers.size(); i++)
{
//Not sure what the best approach here would be and I'm not even sure if I should have done a vector...
}
为什么要读入数字向量,为什么在读取每一行时不直接写入rowcol?
// Check myfile and not only myfile.eof()
int row, column, value;
while(myfile >> row >> column >> value) {
rowcol[row][column] = value;
}
此代码不会检查一行中只有3个数字,具体取决于您可能需要为此添加检查的要求。
只需阅读行,列值和更新行列即可:
int rowcol[8][8];
for (int i=0; i < 9; i++)
for (int j=0; j < 9; j++)
{
rowcol[i][j] =0;
}
myfile.open(text.c_str());
while (!myfile.eof()) {
int row, col, val;
myfile >> row >> col >> val;
rowcol[row][col] = val;
}
更好的解决方案是使用一个数字来指示行数:
// file struct
2
0 0 1
0 1 2
template< typename T >
inline T read( std::istream& is )
{
T res;
is >> res;
return res;
}
int rowcol[8][8];
for (int i=0; i < 9; i++)
for (int j=0; j < 9; j++)
{
rowcol[i][j] =0;
}
myfile.open(text.c_str());
const size_t COUNT = read<int>( myfile );
for ( int i = 0; i < COUNT; ++i )
int row = read<int>( myfile );
int col = read<int>( myfile );
int val = read<int>( myfile );
rowcol[row][col] = val;
}
您的代码无效。 如果定义了一个数组,该数组的维度大小等于8,则在循环中应使用条件i <8而不是i <9
int rowcol[8][8];
for (int i=0; i < 9; i++)
for (int j=0; j < 9; j++)
{
rowcol[i][j] =0;
}
此外,可以在定义数组时进行此类初始化
int rowcol[8][8] = {};
至于从文件中读取记录的代码,则应检查每一行是否正好包含三个数字,并且前两个数字是否具有可接受的数组索引值。
你可以使用向量
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<int> split(string line,char delm)
{
vector<int> tokens;
string num="";
for(int i=0;i<line.length();i++)
{
char c = line[i];
if(c == delm)
{
tokens.push_back(atoi(num.c_str()));
num="";
}else
{
num+=c;
}
}
return tokens;
}
string text="file.txt";
int main()
{
string line = "";
ifstream infile;
infile.open(text.c_str());
vector<vector<int>> mydata;
while (!infile.eof())
{
getline(infile, line);
mydata.push_back(split(line,' '));
}
infile.close();
system("pause");
return 0;
}
如果要将其转换为数组
int rowcol[8][8];
for (int i=0; i < mydata.size(); i++)
{
vector<int> d = mydata[i];
for (int j=0; j < d.size(); j++)
{
rowcol[i][j] =d[j];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.