Can someone please show me how I can print out a second column of values (array) to supplement my first column in my "User" array. That is read from a .txt file.
Please note that you will need to create a separate .txt with a list of users (down) to get the code to work.
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
int array_size = 1024;
char * array = newchar[array_size];
//int arrayValues[];//declaring new array for values
int position = 0;
ifstream fin("userList.txt");//data file for list of users array
//ifstream value("userValues.txt");// read integers from data file, for use in array and supplement to list of users array
if(fin.is_open())
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
while(!fin.eof() && position < array_size)
{
fin.get(array[position]);
position++;
}
array[position-1] = '\0';
cout << "Displaying Array..." << endl << endl;
for(int i = 0; array[i] != '\0'; i++)
{
cout << array[i];// this code works for only displaying 1 array of a user list
/*
//cout << array[i]<< setw(13) << userValues[i]<<; print out list of user array and associate values to the users?
*/
}
}
else
{
cout << "File could not be opened." << endl;
}
return 0;
}
Line 23: You're reading the file character by character. This is not how you want to do it.
You haven't shown us the format of the input file, so I can't tell you the correct way to do this.
Line 42: You never delete the array you allocated at line 8. This is a memory leak.
Line 21: Do not loop on !eof(). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> operation as the condition in the while statement.
1 2 3
while (cin >> var)
{ // Good cin or istream operation
}
{
int number; //Variable to hold each number as it is read
int array_size = 1024;
char * array = newchar[array_size];
int position = 0;
//Create a dynamic array to hold the values
vector<int> numbers;
ifstream fin("userList.txt");
//Create an input file stream
ifstream in("userValues.txt");
while (in >> number)
{
//Add the number to the end of the array
numbers.push_back(number);
}
if(fin.is_open())
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
while(!fin.eof() && position < array_size)
{
fin.get(array[position]);
position++;
}
array[position-1] = '\0';
cout << "Displaying Array..." << endl << endl;
for(int i = 0; array[i] != '\0'; i++)
{
cout << array[i] << numbers[i] << '\n';;
}
}
else
{
cout << "File could not be opened." << endl;
}
}