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

标签 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 input要读的话,所以会停止读文件。我该如何处理?

最佳答案

如果用以下内容替换“while”循环会怎样?

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

当然,请确保包含“字符串” header

关于c++ - 如果我只想读取数字,如何忽略文本文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320071/

相关文章:

c++ - 我如何在我的构造函数中将 weak_ptr 分发给它?

c++ - 在 CUDA 中使用 SIMD 实现位循环运算符

c++ - 测量 CPU 时钟速度

c++ - 使用点云库 (PCL) 时的 Boost 问题

c++ - 使用 std::fstream 会导致程序在 PASE for i (7.3) 中以 SIGILL 结束

c++ - OpenCV 中的快速颜色量化

c++ - 使用程序作为包含主要功能的库

c++ - Qt:更改 QFileInfo 对象中的图标

c++ - 使用未命名的命名空间重新定义 API 中的友元类并访问私有(private)成员?

c++ - 将 C 代码转换为 C++、将 double* 转换为 vector 、将 2D vector 转换为 double*