我想在C ++中阅读以下文件。
000001011100110
100000010101100
001001001001100
110110000000011
000000010110011
011000110101110
111010011011110
011001010010000
我知道文件中有多少rows
和columns
。我想阅读每个integer
并将其存储在2-D matrix
的整数中。
这里的每个整数表示0
是一个条目,1
是另一个条目。因此,在上面的示例中,有15
0
和1
s。
答案 0 :(得分:1)
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << endl;
int lineNumber;
stringstream(line) >> lineNumber;
//Do smith with this line read amount of digits
int tempNumber = lineNumber;
num_digits = 0;
//get number of digits
while(tempNumber > 0) {
num_digits++;
tempNumber/=10;
}
//print digits
std::stringstream tmp_stream;
tmp_stream << tempNumber;
for (i = 0; i < tmp_stream.str().size(); i++)
{
std::cout << "Digit [" << i << "] is: " << tmp_stream.str().at(i) << std::endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
//获取位数 是一些额外的,也许你会找到一个更好的获取数字的方法,所以这可能是有用的
完全符合您的目的,只需要这样做:
if (myfile.is_open()){
int line = 0;
while ( getline (myfile,line) )
{
cout << line << endl;
for (i = 0; i < line.size(); i++)
{
std::cout << "Digit [" << i << "] is: " << line.at(i) << std::endl;
int lineDigitNumber;
stringstream(line) >> lineDigitNumber;
}
line++;
//Fill array with line and i
}
myfile.close();
}
答案 1 :(得分:1)
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
const size_t NROWS = /* number of rows */;
const size_t NCOLS = /* number of cols */;
int main () {
vector<vector<int> > myvec (NROWS, vector<int>(NCOLS));
ifstream myfile ("example.txt");
if (myfile.is_open ())
{
string line;
for (size_t rowcount = 0; rowcount < NROWS && getline (myfile, line);
++rowcount)
{
size_t colcount = 0;
for (string::const_iterator it = line.begin ();
it != line.end () && colcount < NCOLS; ++it, ++colcount)
{
myvec[rowcount][colcount] = *it - '0';
}
}
myfile.close ();
}
else
cerr << "Unable to open file" << endl;
return 0;
}
关于std::vector<T>
的一个巧妙的事情是构造函数(size_t, T& default_value = T())
都预分配和分配。
因此,使用它制作多维数组非常容易 - 只需根据需要嵌套向量,并为第二个参数嵌套(n-1)
级别。
答案 2 :(得分:0)
这是我使用quick'n'dirty矩阵类实现的“练习”;)
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
class CMatrix {
public:
CMatrix(unsigned int r, unsigned int c)
: rows(r), cols(c), a(new int [r*c])
{}
// copy constructor and copy assignment operator come here
~CMatrix()
{
delete [] a;
}
int& at(unsigned int r, unsigned int c)
{
if (r >= rows || c >= cols) throw std::out_of_range("Out of range access");
return a[r*cols + c];
}
private:
unsigned int rows;
unsigned int cols;
int* a;
};
int main()
{
// assuming the sample file OP provided
const unsigned int n_rows = 8;
const unsigned int n_cols = 15;
std::ifstream myfile("in.txt");
if (!myfile.is_open()) {
// report error
} else {
CMatrix matrix(n_rows, n_cols);
std::string line;
unsigned int m = 0;
unsigned int n = 0;
while (getline(myfile, line))
{
n = 0;
for (char& c : line) {
matrix.at(m,n) = c == '0' ? 0 : 1;
++n;
}
++m;
}
}
}