0

Estaba trabajando en leer un txt y colocarlo en otro pero sucede que la primera y ultima linea, son lineas que no quisiera tener porque son innecesarias, quisiera saber como podría eliminarlas sin tener que hacer un if para que no las copie simplemente. Quizás haya alguna función predefinida o una librería que me permita hacer eso. Este es mi código:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


void lectura(){
    ifstream file;
    ofstream rewrite;
    string texto;
    //Leo el pdf y abro.
    rewrite.open("Final.txt", ios::out);
    file.open("Tarea_10.txt", ios::in);

    //recorre mientras no halla final.
    while(!file.eof()){
        string id = " ";
        string newtext;
        int counter = 0;
        getline(file, texto);

        // sustraer con string go = texto.substr(10, 20);
        // saca el id.
        for (int i = 0; i < texto.length(); i++)
        {
            if (texto[i] == ',')
            {
                newtext = texto.substr(i, texto.length());
                for(int j = 0; j < newtext.length(); j++)
                {
                    if(newtext[j] == ' ' || newtext[j] == ',' || newtext[j] == '-' || newtext[j] == '"')
                    {
                        counter ++;
                    }
                }
                break;
            }
            id += texto[i];
            // cout << "ID: " << texto[i];
        }
        rewrite << "ID: " << id << " = " << counter << " || Descripccion:  " << newtext.substr(0,15) << "..." << endl;
        rewrite << endl;

        //cuenta las palabras.
    }
    
    rewrite.close();
    file.close();
}

int main(){
    lectura();
}

Basicamente mi txt se ve así:

ID:  id = 1 || Descripccion:  ,description...

ID:  1 = 171 || Descripccion:  ,"Active classi...

ID:  2 = 178 || Descripccion:  ,"Active sport ...

ID:  3 = 144 || Descripccion:  ,"Active sport ...

ID:  4 = 228 || Descripccion:  ,"Alpine guide ...

ID:  5 = 308 || Descripccion:  ,"Alpine wind j...

ID:  6 = 250 || Descripccion:  ,"Ascensionist ...
.
.
.
ID:  498 = 212 || Descripccion:  ,"All-time shel...

ID:  499 = 150 || Descripccion:  ,"All-wear carg...

ID:  500 = 134 || Descripccion:  ,"All-wear shor...

ID:   = 0 || Descripccion:  ...

Y de donde lee el txt es así: ``` id,description 1,"Active classic boxers - There's a reason why our boxers are a cult favorite - they keep their cool, especially in sticky situations. The quick-drying, lightweight underwear takes up minimal space in a travel pack. An exposed, brushed waistband offers next-to-skin softness, five-panel construction with a traditional boxer back for a classic fit, and a functional fly. Made of 3.7-oz 100% recycled polyester with moisture-wicking performance. Inseam (size M) is 4 1/2"". Recyclable through the Common Threads Recycling Program.

Details:

  • ""Silky Capilene 1 fabric is ultralight, breathable and quick-to-dry""
  • ""Exposed, brushed elastic waistband for comfort""
  • 5-panel construction with traditional boxer back
  • ""Inseam (size M) is 4 1/2""""""


Fabric: 3.7-oz 100% all-recycled polyester with Gladiodor natural odor control for the garment. Recyclable through the Common Threads Recycling Program

Weight: 99 g (3.5 oz)

Made in Mexico." 2,"Active sport boxer briefs - Skinning up Glory requires enough movement without your boxers deciding to poach their own route. The form-fitting Active Sport Boxer Briefs are made from breathable 93% polyester (71% recycled) fabric that's fast-wicking, dries quickly and has 7% spandex for stretch; the seamless waistband and soft leg edges won't roll or bind. The gusseted, flat-sewn 6"" inseam (size M) is offset to prevent inner-thigh chafe. Fly-free with a smooth front panel. Recyclable through the Common Threads Recycling Program.

Details:
  • ""Stretch mesh provides support, open-weave mesh for airflow, wicks efficiently, dries fast""
  • Seamless construction
  • ""Flat-sewn, gusseted inseam is set forward to prevent inner-thigh chafe""
  • Fly-free support
  • ""Inseam (size M) is 6""""""


Fabric: ""4.6-oz 93% polyester (71% recycled)/7% spandex, with moisture-wicking performance. Recyclable through the Common Threads Recycling Program""

Weight: (60 g 2.1 oz)

Made in Israel." . . . 498,"All-time shell - No need to use that morning Times as an umbrella. The All-Times' handsome matte-finish, 100% recycled polyester shell provides tasteful sports-coat-length coverage for the vicissitudes of weather in the city and country. A hardy 2.5-layer, 4.2-oz polyester ripstop with an H2No waterproof/breathable barrier and a Deluge DWR (durable water repellent) finish scoffs at cloudbursts; a 100% polyester (60% recycled) brushed fleece collar lining and chin guard keep you feeling well-kept, and the zip-off hood gives you options and keeps you dry. The 2-way zip allows for flexibility when sitting. Recyclable through the Common Threads Recycling Program.

Details:
  • 2.5-layer 100% all-recycled polyester shell with a matte ripstop surface and a waterproof/breathable H2No barrier
  • ""Snap-off detachable storm hood, protective microfleece-lined collar and chin guard""
  • 2-way zip
  • Laser-cut zippered handwarmer pockets


Fabric: ""Shell: 2.5-layer, 4.1-oz 50-denier 100% all-recycled polyester ripstop with a waterproof/breathable H2No barrier and Deluge DWR (durable water repellent) finish. Collar lining and chin guard: 4.2-oz 100% polyester (60% recycled) brushed fleece. Recyclable through the Common Threads Recycling Program""

Weight: 493 g (17.4 oz)

Made in China." 499,"All-wear cargo shorts - All-Wear Cargo Shorts bask in the glory of sweat stains, paint splatters and caked-on mud - and get the job done every time. Resilient, garment-washed 5.2-oz 100% organic cotton canvas softens with each washing. Offset side seams won't chafe during active use. Has a classic flat front with two generous wide-entry drop-in pockets, two bellowed side cargos and two rear welted pockets. Inseam (size 32) is 12"". Recyclable through the Common Threads Recycling Program.

Details:
  • Lightweight organic cotton canvas
  • Zip fly with button closure
  • Flat front with offset side seams
  • Generous wide-entry front pockets
  • Welted back pockets hidden under yoke
  • ""Inseam is 12""""""


Fabric: 5.2-oz 100% organic cotton canvas. Recyclable through the Common Threads Recycling Program

Weight: (349 g 12.1 oz)

Made in Thailand." 500,"All-wear shorts - Time to simplify? Our All-Wear shorts prove that one short really can go anywhere. Made from comfortable garment-washed 100% organic cotton canvas, they withstand hard work and arduous journeys and remain unfazed. Durable but soft to the touch, they feature two wide-entry drop-in front pockets, two rear welted pockets and an 8 1/2"" inseam (size 32). Recyclable through the Common Threads Recycling Program.

Details:
  • Lightweight yet durable organic cotton
  • Flat front
  • Zip fly with button closure
  • Generous wide-entry drop-in front pockets
  • Welted back pockets
  • ""Inseam is 8 1/2""""""
  • Updated fit


Fabric: 5.2-oz 100% organic cotton canvas. Recyclable through the Common Threads Recycling Program

Weight: (282 g 9.8 oz)

Made in Thailand."

1 respuesta 1

0

Para evitar que te escirba la primera linea es tan simple como antes del bulce while poner un getline(file, texto);. Así cuando entres en el bucle empezará a leer y a escribir apartir de la segunda linea. Para que no escriba la última es un poco más complicado (ya que según como está hecho el while no se sabe si es la última vuelta o no) y hay varias maneras de hacerlo pero habría que cambiar la estructura de tu while.

Una opción es que crees dos variables tipostring una que almacene la linea anterior(lineaAnterior) y otra que almacene la linea actual(lineaActual) en el bucle haces lo siguiente:

  1. pasas el valor de lineaActual a lineaAnterior
  2. Lees una linea y la guardas en lineaActual
  3. Haces lo mismo que tienes hecho en el while pero cambias los lugares donde tengas puesta la variable texto por lineaAnterior. (Y obviamente quitas el getline que tienes puesto tu dentro del while)

Y haciendo eso la última linea no se leerá. Tienes que tener en cuenta que antes de entrar al while también te haría falta leer una linea y guardarla en la variable lineaActual que sumado con el getline para que no se lea la primera linea hacen 2 getline(file, lineaActual) antes de entrar al while.

De todas maneras creo que no existe ninguna función predeterminada que haga lo que pides, es cosa tuya conseguir que tu programa lo haga.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.