簡體   English   中英

如何在C ++中讀取文件?

[英]How to read a file in c++?

我試圖在我的方法“加載”中讀取文件。 這個文件是這樣的:

3
3 Futech tablet 2 7.95
1 El_general_en_su_laberinto Gabriel_García_Márquez 23.50
2 Carne_picada 1 4.56

第一行是項目數,我的方法應加載並打印如下內容:

3 Futech tablet 2 7.95

這是我的類與我的方法加載

    #include "ItemProccesor.h"
    #include<string>
    #include<iostream>
    #include<fstream>
    #include <stdlib.h>

    using namespace std;

    ItemProcessor::ItemProcessor() {
        // TODO Auto-generated constructor stub

    }

    ItemProcessor::~ItemProcessor() {
        // TODO Auto-generated destructor stub
    }

    void ItemProcessor::load(string archivo){
int tam;
        int tipo;
        int cant;
        string cad1;
        string cad2;
        float precio;
        ifstream myfile;
        myfile.open(archivo.c_str());
        if (myfile.is_open()){
            myfile >> tam;

            for(int n= 0; n < tam; n++) {
                myfile >> tipo;
                cout << tipo << cad1;
            }
        }
        myfile.close();

    }

其實我的方法打印:

333

就像總是走同一條線。 這是我的方法主要:

#include <iostream>
#include <string>
#include "ItemProccesor.h"

int main(int argc, char **argv) {
  ItemProcessor *processor = new ItemProcessor();
  processor->load("lista.txt");

}

¿我如何轉到下一行?

不知道這是否是唯一的問題,但是您兩次閱讀了tipo 嘗試更換

myfile >> tipo >> cad1 >> cad2 >> cant >> precio;

myfile >> cad1 >> cad2 >> cant >> precio;

您的輸入文件似乎被弄亂了。 有時一行有四列,有時五列,有時三列。

這使得很難閱讀!

如果無法修復文件,則必須一次性讀取每一行,然后使用令牌生成器在空格處拆分行,以便可以在處理該行之前計算每一行中有多少列。

您的方法是打印333,因為您根本沒有遍歷所有行。


  void ItemProcessor::load(string archivo){
            int cant;
            float precio;
            string tipo, cad1, cad2, line;

            ifstream myfile(archivo.c_str());
            if(myfile.is_open())
            {
                while(getline(myfile,line))
                {
                     myfile >> tipo >> cad1 >> cad2 >> cant >> precio;
                     cout << tipo << " "<< cad1 <<" "<< cad2 <<" "<<cant <<" "<< precio << endl;
                }
            }
            else
                cout <<"error " << endl;
            myfile.close();
        }

產量

3 Futech tablet 2 7.95
1 El_general_en_su_laberinto Gabriel_García_Márquez 23 0.50
2 Carne_picada 1 4.56

有趣的是它將23.50轉換為23 0.50 不知道為什么,但是哦,洛洛洛爾。 至少有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM