Let's say there's list of numbers like this saved in a txt file:
4 6 3 4 5
How do I put it into an array?

Recommended Answers

All 7 Replies

I want to put it in an integer array with a for loop. Your link doesn't really help.

Pseudo:

Read first integer from text file
put it in Array[0]
Read second integer from text file
put it in Array[1]
...

With a for loop, it would look something like this:

for (i=0; i < sizeOfArray; i++)
   put integer into Array[i]

I don't know what to put inside of the for loop

How would assign a value to an element of the array?

Pretty much the same you assign a value to a plain int.

Your loop is fine, if you know exactly how many values are in the data file, and that number is the size of the array. Usually a better choice is a while loop in which the stopping conditions are not having any more room in the array or having run out of data to read, whichever comes first.

It works if you have the numbers written one per line. What if I wanted to read them from one line, where the numbers are separated by spaces?

try this:

int a, b, c;

cin >> a >> b >> c;

When this runs, type the following
1 2 3 <enter>

Does it work?

Yes, it does! Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.