1

A text file looks like this:

3
String
String2
String3

I must create a function to read all the strings from text file, save them to array and then display it in main function. For example

void reading(int & count, string strings[]) {
ifstream fd "text.txt";
fd >> count;
for (int i=0; i<count; i++)
fd >> strings[i];
fd.close();

And main function:

int main() {
int count=0;
string strings[100];
reading(count, strings);
for (int i=0; i<count; i++) 
cout << strings[i] << endl;

The number of strings is written in first line of text file. How can I create an array of exactly that number? I need it to be able to access it in main/other functions. (For example function for writing into another text file).

2
  • 1
    Can you use a std::vector<std::string> instead of an array? Commented Jul 29, 2016 at 21:37
  • I wanna be honest with you... It's really cool helping someone but you should always consider that we have to start somewhere. That means you have to start before you can cross the finish line Commented Jul 29, 2016 at 21:54

3 Answers 3

4

In case there is a super important reason to do that with an array, then use std::new, like this:

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

int reading(string** str_array, int& size,  string filename) {
    ifstream infile(filename.c_str());
    if(!infile) {
        cerr << "Unable to access file!\n";
        return -1;
    }
    int n = 0;
    infile >> size;
    try{
        *str_array = new string[size];
        string str;
        for (; n < size && infile; ++n) {
            infile >> str;
            (*str_array)[n] = str;
        }

        if (n != size)
            cerr << "ERROR, read less than " << size << " strings!!\n\n";
    } catch(bad_alloc& exc) {
        return -2;
    }
    return 0;
}


int main() {
    string* str_array = NULL;
    int size;
    if(reading(&str_array, size, "test.txt")) {
        cerr << "Din't read file, exiting...\n";
        return -1;
    }
    for(int i = 0; i < size; ++i)
        cout << str_array[i] << endl;

    delete [] str_array; // DO NOT FORGET TO FREE YOUR MEMORY
    str_array = NULL;

    return 0;
}

Output:

C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3

However, you are in and you are not using an std::vector for this?

Look how simple it is with that:

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

int reading(vector<string>& v, string filename) {
    ifstream infile(filename.c_str());
    if(!infile) {
        cerr << "Unable to access file!\n";
        return -1;
    }
    int N = -1, n = 0;
    infile >> N;
    string str;
    for (; n < N && infile; ++n) {
        infile >> str;
        v.push_back(str);
    }

    if (n != N)
        cerr << "ERROR, read less than " << N << " strings!!\n\n";
    return 0;
}

int main() {
    vector<string> v;
    if(reading(v, "test.txt")) {
        cerr << "Din't read file, exiting...\n";
        return -1;
    }
    for(size_t i = 0; i < v.size(); ++i)
        cout << v[i] << "\n";
    return 0;
}

Output:

C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3

Edit:

We have to pass a pointer to what we want to modify (that is, the string*), otherwise the changes we apply won't take place. Test it yourself, pass a string* as a parameter instead of string**, modify the body of the function and she what happens.

To get the idea, imagine we want to write to the pointer, the new address, which new gave us and holds the memory requested. We do write that address inside the function, but when the function terminates, we want the changes to be persistent. See my Functions in C as an example.

Sign up to request clarification or add additional context in comments.

10 Comments

This is likely a homework assignment, which IF it is, there are constraints on using things like that in class.
@M4rc making assumptions on this is something that should be a part of the logic the person that answers has to follow, I mean what the heck?! If it is homework, then state it. But OK, I will provide another version too then...
I agree. Ideally people would tag these things accordingly. But since when have we lived in an ideal world? The only reason I assume it's homework is because many moons ago I had to do a similar program. But then again, there are people on SO that ask people how to program an entire CLI interface.
@M4rc that's true...Nevertheless, I updated my post, is it good?
Very much so =]. Thing I love about programming -- there's more than 1 way to get to the intended end result. I would set str_array = 0; after the delete statement though, but that's only because old habits die hard in checking/leaving dangling pointers.
|
2

Allocate an array on the heap, like this:

std::string* stringArr = new std::string[(place amout of strings here)];

and don't forget to delete it at the end of main()

delete stringArr[];

Variables / arrays on the heap are dynamic so the size doesn't have to be fixed!

std::string* → This is a pointer that points to the address of the beginning of this array in your memory. (Just to let your computer know where it is)

stringArr → the name of the array

new → allocates new memory

std::string[size] → says how much to allocate

I've seen some answers that were talking about "vectors". If you wanna use them you could have a look at this page for more info! → Vector documentation

8 Comments

You should use a vector instead, as it will take care of managing memory for you.
@Kariem It would but before you should get to know a vector you should learn the basics! Cause a vector uses memory on the heap
+1 - Understanding the values of fundamentals behind how vectors, maps, etc. work is far more relevant than simply following the mob mentality of throwing a STL container at everything.
@tistCoder Of course it uses memory on the heap.... I said it manages the memory for you, so when it goes out of scope it will release the memory on the heap that it has allocated.
@M4rc Thanks for that. It looks like it's his homework and the matter of them is to learn an understand
|
0

use a vector

#include <vector>
#include<fstream>
#include <iostream>
using namespace std;
void reading(int & count, vector<string> * strings) {
    ifstream fd("text.txt");
    fd >> count;
    string T;
    for (int i=0; i<count; i++)
    {
        fd >> T;
        strings->push_back(T);
    }
    fd.close();
}

int main() {
    int count=0;
    vector<string> strings;
    reading(count, &strings);
    for (int i=0; i<count; i++) 
        cout << strings[i] << endl;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.