0

I have a line file. I want to put each of its lines into an array, but I need to know the exact size of the space occupied by the array. How can I recognize it? Will the following code work:

#include <fstream>

using namespace std;

void main()
{
  ifstream* file = new ifstream("file.txt");
  string str;
  
  long int count; 
  long int sizeArray;
  while(*file >> str)
  {
    count++;
    sizeArray += sizeof(str) * sizeof(char);
  }
  file->clear();
  file->seekg(0);
  string* array = new string[count];
  long int place = 0;
  while(*file >> str)
  {
    array[place] = str;
    place++;
  }
  
  // sizeArray worked?
  cout << sizeArray << endl;
  
}
artemgh
  • 103
  • 5
  • `sizeof(str)` is the size of a `std::string` object, which does not include the size of its contents. – Eljay May 30 '22 at 16:04
  • `sizeof(str)` is a compile-time constant and is completely unrelated to the text that `str` it represents. Use `str.size()` to know how many characters a `std::string` contains. – François Andrieux May 30 '22 at 16:04
  • 1
    `void main()` is not valid in C++. And why are you using `new` for the `ifstream`? You never `delete` it ... Ditto with your array. Use a `vector` instead. – ChrisMM May 30 '22 at 16:06
  • If you use a `std::vector` you will not have to know in advance how many lines are there in the file. – wohlstad May 30 '22 at 16:06
  • @ChrisMM I always use int main, it's just to avoid writing return and make the code in the question smaller) – artemgh May 30 '22 at 16:07
  • 1
    This code shows a significant over-use of `new`. If you are coming from a high level object oriented language like C# of Java this may seem like the normal thing to do to create an object. But in C++ it is only used to create objects with a dynamic lifetime, one whose lifetime is not tied to its scope. And even then, `std::make_shared` and `std::make_unique` should be used instead. But here you can use objects automatic lifetime by using `std::ifstream file("file.txt");` and `std::string array;` instead. `new` should almost never be used in modern C++ code. – François Andrieux May 30 '22 at 16:07
  • 1
    @artemgh, you don't need a `return` in `main` in the first place. Putting `void main()` makes the code invalid though, and it will not compile in any compiler that follows the standard. See [examples here](https://godbolt.org/z/r89YfdxzM) (MSVC allows it with warning, because it's a bit dumb). – ChrisMM May 30 '22 at 16:09
  • @ChrisMM You are right, I will – artemgh May 30 '22 at 16:10
  • @FrançoisAndrieux Thank you, I will keep it in mind – artemgh May 30 '22 at 16:15
  • Please see idiomatic C++ code: https://wandbox.org/permlink/SNaWLP7pzG6s24Ae – Marek R May 30 '22 at 16:19

0 Answers0