0

I want to read a txt file and I want to process each number on the line one by one, apply some functions and pass to the other line. When the line is over, I don't know how to apply the same operations to the lines below. Methods will get a different output from each line that is why I have to handle each line separately.

int number;
ifstream readingFile("a.txt");

while(readingFile >> number){
    /* Methods will be applied to each number in the line */
}

readingFile.close();

a.txt

23 4 555

2123 44 21 4

1 45 667 2 112

Duke II
  • 15
  • 1
  • 6
  • 5
    Read the whole line with std::getline() into a std::string then use a istringstream to get the numbers out of the string. – drescherjm Aug 15 '20 at 20:54
  • 2
    Related if not a duplicate: [https://stackoverflow.com/questions/36365202/c-reading-lines-of-integers-from-cin](https://stackoverflow.com/questions/36365202/c-reading-lines-of-integers-from-cin) – drescherjm Aug 15 '20 at 20:57
  • Does this answer your question? [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – wrestang May 17 '22 at 18:42

1 Answers1

-1

Working C++ Code

To clear doubts Test it in https://www.tutorialspoint.com/compile_cpp11_online.php Just copy-paste execute

#include <iostream>
#include <string> 
#include <sstream>
#include <fstream> 
int main () 
{   
    //code create a file with numbers
    std::ofstream myfile;
    myfile.open ("file.txt");
    myfile << "123 12  32323\n 4444 55 535\n";
    myfile.close();
    
    std::ifstream input( "file.txt" );
    for( std::string eachLine; getline( input, eachLine ); )
    {
        std::istringstream strm(eachLine);
        std::string splitedLines;
        // loop for each string and add to the vector
        while ( strm >> splitedLines )
            {
            std::stringstream geek(splitedLines);
            int num;    // can be int, float or double
            geek >>num;
            //perform action on all num in each line one by one 
            std::cout<<num<<std::endl;
            }    
        }
    return 0; 
}

Edit: PythonCode read numbers one by one in each line

fileName = open('a.txt', 'r')
line = fileName.readline() //reading first line
while(line):
    for eachStringNumber in line.split():
        number = int(eachStringNumber)
        /// Methods will be applied to each number in the line ///
    line = fileName.readline() // reading lines one by one in each loop
fileName.close()
Darshan K N
  • 113
  • 8