Uaga
Uaga

Reputation: 41

Store lines from a text file in a list of strings

I've been trying to store the lines of a text file in a list in C++. Better, I've been trying to store each word of each line of the text file in a string that is part of a list of strings, but it seems that I'm doing it in the wrong way.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <list>

using namespace std;

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


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

The exact problem is that this doesn't give any result. It compiles but nothing results from this.

Thanks in advance.

Upvotes: 3

Views: 4400

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Change your while loop as follows:

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

You cannot access any non initialized items from a std::list<>.

Also NOTE you should make line a std::string, and omit the malloc() / free() calls from your code.

2nd NOTE: Use std::ifstream instead of FILE* for an input file stream.

Here's the fully fixed (no more errors/exceptions on ideone) code sample:

#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);
}

Upvotes: 2

Shashwat Kumar
Shashwat Kumar

Reputation: 5297

You can not assign a char* value to std::string by using '=' operator.

Change

*it=line to

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

Upvotes: 1

Related Questions