[英]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.