0

I have this file:

4
10 3 4 6

The first line declares how many numbers the second line has.I want to put the numbers of the second line in an array.So far i have been using this loop to automatically declare how many numbers the second line has and how many times to do the loop:

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

using namespace std;

int main(){
    ifstream infile;
    infile.open("input.in");
    string kids;
    int x;
    int i;
    getline(infile,kids);
    cout << "The Number Of Kids Is " << kids << endl;
    istringstream buffer(kids);
    int kidss;
    buffer >> kidss;
    for(i=0;i<kidss;i++){
        infile >> x;
        cout << x << " ";
    }
    infile.close();
    return 0;
}

Now i want to do the same thing but instead of inputing the numbers in x i want to put them in an array and then display them as above.Thanks In Advance!

1
  • Use a std::vector and the push_back() function. Commented Jan 5, 2015 at 10:37

1 Answer 1

3

The best way of doing this would be with a std::vector these are variable length arrays in c++.

To use them in this case you would do

std::vector<int> array;
for( int i = 0 ; i < kidss ; ++i ) {
    infile >> x;
    array.push_back(x);
}

Then if you wanted to print them out again you would be able to do

for( int i = 0 ; i < array.size() ; ++i ) {
    std::cout << array[i] << " ";
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would better recommend the reference link I've put in my comment on the question.
@πάνταῥεῖ : Answers are better than comments, answers in comments are not good SO practice, neither are link only answers, so as a link only answer in a comment, your "answer" has little to recommend it in the context of SO.
It wasn' an answer, but a comment.

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.