I am a beginner level C++ student, so please forgive me if I use the wrong terminology here....I need to create a program that takes a set of integers from a source file, tells whether the numbers are odd or even integers, and then adds the odds and the evens (separately, of course). I'm not looking for the answers to the problem, I just need the answer to the following question, in order to get started....

How do I take one file and input, say 10 numbers, without having to identify each one as int1, int2, int3, etc.?

Edited by PDB1982: n/a

7 Years
Discussion Span
Last Post by PDB1982

Make a vector or an array (worse but easier), and then read numbers from a file (using fstream).


how do I do that though? I have covered loops in class, but not vectors or arrays.....

Edited by PDB1982: n/a


Array is a set of succeeding variables of defined type, and in c++ they are used/declared using [], for example by writing int table[10]; you declare an array with 10 elements of type int(you access them by using table[0] for first element and so on). Vector is c++ standard template, it's easier to use (you will find out fast) "type" off array, google it for help.
After declaring <fstream>, you can make a new variable (ifstream file("filename.txt");) which you can use just like cin stream to read data. Make a for loop, and your program is ready.


is this how my code should look then? I'm a bit confused about how to specify to the program that it should add the odd integers, then add the even integers....

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

const int sum = 0;

void main()
	int table[10];
	ifstream infile;


	cout << "Your Integers Include\n";
	infile >> table[0] >> table[1] >> table[2] >> table[3] >> table[4] >> table[5] >> table[6] >> table[7]
		>> table[8] >> table[9];
		cout << table[0] << table[1] << table[2] << table[3] << table [4] << table[5] << table[6] << table[7] 
			<< table[8] << table[9]<< endl;

	while (true)
		if (table[10] % 3 != 0)
			cout << table[10] + sum;
			cout << table[10] + sum;


Table[10] is invalid, you declared array with 10 elements and this instruction would try to access 11th. You should use some for loops, for example:

for (int i=0; i<10; i++){

will print all elements of the array "table". Also your program will go on forever, because there is no exit from while loop.


Thanks for your help....I'm completely lost, so I think I better search back through the book again.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.