如果我只想读取数字,如何忽略文本文件中的单词

时间:2015-10-24 15:47:33

标签: c++

以下是我想处理的txt文件类型,只读取每个链接后的数字:

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
...

这是我的代码:

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

outfile总是空白的,我认为是因为我的int输入会读取单词,所以它会停止读取文件。我怎么处理它?

2 个答案:

答案 0 :(得分:1)

如果您更换&#39;&#39;循环使用以下内容?

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

当然,请确保包含&#39; string&#39;头

答案 1 :(得分:0)

如果您知道输入文件的每行总是有三列,则可以在while条件下一次保存3个值。

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