Leon Ma
Leon Ma

Reputation: 303

How do I ignore words from a text file if I only want to read the numbers

Here is the type of txt file I want to process to read only the numbers after each link:

http://example.com/object1   50   0
http://example.com/object2   25   1
http://example.another.com/repo/objects/1   250   0
ftp://ftpserver.abc.edu:8080   13   5
...

And here is my code:

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <fstream>

using namespace std;

int main() {
    // input file
    ifstream infile;
    infile.open("ece150-proj1-input.txt");

    // output file
    ofstream outfile;
    outfile.open("ece150-proj1-output.txt");


    int input;
    int column = 0; // couting number of columns
    int row = 0; // couting number of rows
    int size = 0;
    int delay = 0;

    // calculation
    while (infile >> input) {       //------> Problem starts here
        switch ((column+3)%3) {
            case 1:
                size = size + input;
                row++;
                break;
            case 2:
                delay = delay + input;
            default:
                break;
        }
        column++;
    }

    infile.close();

    double averageSize = size/row;
    double expectedDelay = delay/row;
    double expectedTotalDelay = averageSize/1.25 + expectedDelay;

    outfile << "Average size = " << averageSize << endl;
    outfile << "Expected delay for priority = " << expectedDelay << endl;
    outfile << "Expected total delay = " << expectedTotalDelay << endl;

    outfile.close();
    return 0;
}

The outfile is always blank, I think it is because my int input will read the words, so it will stop reading the file. How can I deal with it ?

Upvotes: 1

Views: 2088

Answers (2)

Thejaswi
Thejaswi

Reputation: 26

What if you replace the 'while' loop with the following?

while (!infile.eof()) {
    string url;
    int input1, input2;
    infile >> url >> input1 >> input2;
    size += input1;
    delay += input2;
    ++row;
}

Ofcourse, make sure you include 'string' header

Upvotes: 1

faadi
faadi

Reputation: 176

If you know that you will always have three columns per line of the input file, you can save 3 values at a time in your while condition.

sumDelay = 0;
sumSize = 0;
row = 0;
std::string address;
while (!infile.eof() && (infile >> address >> size >> delay) )
{
        sumSize =+ size;
        sumDelay =+ delay;
        row++;
 }

Upvotes: 0

Related Questions