English 中文(简体)
阅读C++的档案,该档案有分类
原标题:Reading a file in C++ which has integers
  • 时间:2011-11-18 07:36:29
  •  标签:
  • c++

我想读到的是C++。

000001011100110
100000010101100
001001001001100
110110000000011
000000010110011
011000110101110
111010011011110
011001010010000

I know already how many rows and columns is there in the file. I want to read each integer and store it in a 2-D matrix of ints. Each integers here means 0 is one entry and 1 is another entry. So in this example above there are 15 0 s and 1s.

最佳回答
#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;
}

One of the neat things about std::vector<T> is that the constructor (size_t, T& default_value = T()) both preallocates and assigns. Hence, it is very easy to make a multidimensional array with it - just nest the vectors as needed, and nest (n-1) levels for the second argument.

问题回答
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;
}

//get number of digits is some extra, maybe you will fond a better way of getting digits, so this could be useful

这完全是为了你的目的:

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();
}

这里,我“精通”的“精华”,快速实施零 matrix矩阵。

#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;
        }
    }
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签