hi,
i have a txt file "names" containing 300 set of personal info such as:

3765 // id
thomas //last name
barry // first name
876-988776 //phone number
16.37 // a price of what he purchased
8765 // id repeat
dionisio // last name repeat
tom // first name repeat
..... // and so on ...

i am trying to read them into array and cout them in a backward order... however, it stopped displaying content in around the middle... Any body please tell me why.. thanks

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

using namespace std;

int main()
{
	int id[300];
	string lastName[300];
	string firstName[300];
	string phone[300];
	double amount[300];
	
	ifstream reader;
	reader.open("names.txt");
	

	int i=0;
	while(reader>> id[i] >> lastName[i] >> firstName[i] >> phone[i] >> amount[i])
	{
		i++;
		
	}
	//total number is known as i
	int x = i-1;
	
	for(x; x>-1; x--)
	{
		cout<<id[x]<<endl;
		cout<<lastName[x]<<endl;
		cout<<firstName[x]<<endl;
		cout<<phone[x]<<endl;
		cout<<amount[x]<<endl;
	}	
	

	reader.close();
	
	return 0;
}

Recommended Answers

All 3 Replies

what is the value of i when that read loop finishes? Is it greater than 300 ?

what is the value of i when that read loop finishes? Is it greater than 300 ?

the array size, i, is supposed to be 271.. i set x = i-1 //270, the last index for cout...... and then i-- ,,,, up to 0....... i don't know why it doesn't read or display from the beginning of the txt file eventhough if i test with a code like id[0] or lastName[270] , they will give me the right index value

the array size, i, is supposed to be 271.. i set x = i-1 //270, the last index for cout...... and then i-- ,,,, up to 0....... i don't know why it doesn't read or display from the beginning of the txt file eventhough if i test with a code like id[0] or lastName[270] , they will give me the right index value

"Supposed to be" is evil. Never assume. display the value in both loops and be sure.

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.