Save lines from text file to line list

Here is the original problem. #include #include #include #include #include #include

using namespace std;

int main()
{
  ofstream f ("teste.txt");
  size_t len= 100; // valor arbitrário
  char *line;
  std::list<string> mylist;   


if (!f)
  {
    perror("teste.txt");
    exit(1);
  }
  while (getline(&line, &len, f) > 0)
  {
  for (std::list<string>::iterator it = mylist.begin(); it != mylist.end(); it++){
    *it->assign(line,line+strlen(line));
    cout << *it << '\n';
}
   //printf("%s", line);
  }
  fclose(f);
  return 0;
}

Thanks so much for the revised version.

Taking into account,

Uaga

+3
source share
2 answers

Modify the while loop as follows:

  while (getline(&line, &len, f) > 0)
  {
      mylist.push_back(line);     
      cout << mylist.back() << '\n';
  }

You cannot access any uninitialized elements from std::list<>.

Also NOTE you must make linea std::stringand omit calls to malloc()/ free()from your code.

2nd NOTE. Use std::ifstreaminstead FILE*for stream input files.

Here is completely fixed (no more ideone errors / exceptions ):

#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <exception>
#include <errno.h>
#include <stdlib.h>

int main()
{
  try
  {
    std::ifstream f("teste.txt");

    if(!f)
    {
        std::cerr << "ERROR: Cannot open 'teste.txt'!" << std::endl;
        exit(1);
    }
    std::string line;
    std::list<std::string> mylist;   

    while (std::getline(f,line))
    {
        mylist.push_back(line);     
        std::cout << mylist.back() << std::endl;
    }
  }
  catch(const std::exception& ex)
  {
    std::cerr << "Exception: '" << ex.what() << "'!" << std::endl;
    exit(1);
  }

  exit(0);
}
+1

char* std::string "=".

*it=line to

it->assign(line,line+strlen(line);

+1

All Articles