1

How would I add an element to an array, assuming that I have enough space? My code looks something like this:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    ofstream out("hi.out");
    ifstream in("hi.in");
    string currentLine;
    string values[135];/*Enough for worst case scenario*/
    if (out.is_open && in.isopen()){
        while (in >> currentLine){
            /*Add currentLine to values*/
        }
        /*Do stuff with values and write to hi.out*/
    }
    out.close()
    in.close()
    return 0;
}
1
  • 5
    Don't. Use a vector. Commented Sep 14, 2015 at 22:09

2 Answers 2

4

No need to write the loop yourself. With your array:

auto l = std::copy(std::istream_iterator<std::string>(in), {}, values);

l - values is the number of strings read.

Or even better, use a vector, so that you don't have to worry about the possibility of your "worst case scenario" not being the actual worst case scenario.

std::vector<std::string> values(std::istream_iterator<std::string>(in), {});
Sign up to request clarification or add additional context in comments.

1 Comment

I am not really that good at C++, could you explain more to me what this does?
1

You could use an index counter variable:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    ofstream out("hi.out");
    ifstream in("hi.in");
    string currentLine;
    string values[135];/*Enough for worst case scenario*/
    int index = 0;
    if (out.is_open && in.isopen()){
        while (in >> currentLine){
            /*Add currentLine to values*/
            values[index++] = currentLine;
        }
        /*Do stuff with values and write to hi.out*/
    }
    out.close()
    in.close()
    return 0;
}

The variable index, once the loop is complete, will contain the number of strings in your array.

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.