【问题标题】:C ++ files. How to delete a dataC++ 文件。如何删除数据
【发布时间】:2020-05-15 02:41:53
【问题描述】:

我需要帮助,我有一个程序可以读取一个 .txt 文件并将其写入一个新的 .txt 文件,该文件会在开始时向其中添加数据,也就是说,如果我设法做到这一点,那么文件它的内容如下:

4.1 data  
4.2 data  
4.3 data  

我需要的是写但没有“4”。

例如:

1. data  
2. data  
3. data  

到目前为止,我都穿着这个,有人可以帮助我。

...

        #include <iostream>
    #include <fstream>
    #include <stdlib.h>

    using namespace std;

    int main()
    {
        ifstream origen;
        char linea[128];
        char cap[12]="Tema";
        string encabezado= "";
        string nombreArchivo;
        int numEncabezado;

        cout<<"\t\tCARGA ARCHIVO\n"<<endl;
        cout<<"Digite el nombre del archivo o fichero: ";
        getline(cin,nombreArchivo);

        origen.open(nombreArchivo.c_str(),ios::in);
        cout<<"NOMBRE ENCABEZADO"<<endl;
        getline(cin,encabezado);
        cout<<"Numero ?"<<endl;
        cin>>numEncabezado;

        if(origen.fail()){
            cout<<"No se pudo abrir el archivo";
            exit(1);
        }
        else
        {
            ofstream destino("Copia.txt", ios::out|ios::trunc);
            destino<<encabezado<<endl;
            destino<<cap;
            destino<<" "<<numEncabezado<<endl;
            if(destino.fail())
            cout << "Error al cargar nuevo archivo.txt" << endl;
            else
            {
                while(!origen.eof())
                {
                    origen.getline(linea, sizeof(linea));
                    if(origen.good()) // si lectura ok y
                    if(origen.eof())  // si eof, -> termina
                    exit(1);          // el programa
                    else
                    destino << linea << endl;
                    if(destino.fail())
                    {
                        cerr << "Fallo de escritura en archivo" << endl;
                        exit(1);
                    }
                }

                cout<<"\n\t\tArchivo Cargado Correctamente\n"<<endl;
            }
            destino.close();
        }
        origen.close();

        return 0;
    }

【问题讨论】:

  • 你当前的输出是什么样的?
  • 就像你举的第一个例子一样,我想取数字“4”。从你到每一行。
  • 不,我的意思是当你运行代码时你的输出现在是什么样子的?

标签: c++ file io


【解决方案1】:

您提供了大量代码,但没有提供文本文件,所以很难说。但是如果我们假设输入文件总是包含如下内容:

4.1 data  
4.2 data  
4.3 data  

然后,你可以直接替换

destino << linea << endl;

destino << linea[2] << "." << linea.substr(3) << endl;

但是,如果您的输入是,这通常不会起作用

1.12 data
145.1 data

因此,您通常需要指定输入的灵活性。而且您需要代码来处理标题。

【讨论】:

  • ||=== 构建文件:“无项目”中的“无目标”(编译器:未知)===|对于'linea'中的成员'substr',它是非类类型'char [128]'| ||=== 构建失败:1 个错误,0 个警告(0 分钟,0 秒)它给了我一个错误。
猜你喜欢
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
相关资源
最近更新 更多