PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to read file containing a list of integers with an unknown size

 October 29, 2022     arrays, c++, eof, ifstream     No comments   

Issue

I want to read from a file containing an unknown list of 4 integers each. So each line of the file contain something like this"12.0 43.0 19.0 77.0" I thought of using a 2 dimensional array but I don't know the size of the file because its a very big file. I ended up reading each line as a string and used a "while(!in_file.eof())" so I can reach the end of the file but the problem is, I need to get the numbers individually form each line.

Here's a snippet of my code


Solution

You don't need to know how many lines are in your file or how many numbers are in each line.

Use std::vector< std::vector< int > > to store data. If in each line, integers are separated with a space, you can iterate a string of integers and add them one by one to a vector:

#include <iostream>
#include <string>    
#include <stream>
#include <vector>
using namespace std;

int main()
{
    string textLine = "";
    ifstream MyReadFile("filename.txt");
    vector<vector<int>> main_vec;

    // Use a while loop together with the getline() function to read the file line by line
    while (getline(MyReadFile, textLine)) {
    
        vector<int> temp_vec; // Holdes the numbers in a signle line
        int number = 0;

        for (int i = 0, SIZE = textLine.size(); i < SIZE; i++) {

            if (isdigit(textLine[i])) {
                number = number * 10 + (textLine[i] - '0');
            }
            else { // It's a space character. One number was found:
                temp_vec.push_back(number);
                number = 0; // reset for the next number
            }
        }

        temp_vec.push_back(number); // Also add the last number of this line.
        main_vec.push_back(temp_vec); 
    }

    MyReadFile.close();

    // Print Result:
    for (const auto& line_iterator : main_vec) {
        for (const auto& number_iterator : line_iterator) {
            cout << number_iterator << " ";
        }

        cout << endl;
    }
}

Hint: This code works for only integers. For floats, you can easily identify the indices of spaces in each line, get substring of your textLine, and then convert this substring to a float number .



Answered By - ArashV
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing