how to detect new line reading a text file into int array

后端 未结 1 1803
慢半拍i
慢半拍i 2021-01-28 08:15

101 175 123 52 78 184 202 8 219 15 49 254 86 62

156 213 41 200 123 131 252 186 108 116 39 205 243 120

218 239 201 109 52 173 244 58 185 18 64 209 165 222

相关标签:
1条回答
  • 2021-01-28 08:26

    A common approach is to read the file line-by-line, then use istringstream to parse a single line.

    Also as you are using C++, std::vector would be much more suitable for this purpose than the error-prone pointer to pointer.

    A sample looks like this:

    ifstream fin;
    fin.open("numbers.txt");
    
    std::string line;
    std::vector<std::vector<int>> mat; // use vector of vector instead of pointer to pointer
    while (std::getline(fin, line))    // read line-by-line
    {
        cout << line << "\n";
    
        std::istringstream iss(line);  // then process each line separately
        int x;
        std::vector<int> row;
        while (iss >> x)
        {
            cout << x << '\t';
            row.push_back(x);
        }
        mat.push_back(row);
        cout << '\n';
    }
    
    
    // Check the output content
    for( const auto &row : mat )
    {
        for( const auto &x : row )
        {
            cout << x << '\t';
        }
        cout << '\n';
    }
    
    0 讨论(0)
提交回复
热议问题