Thompson Thompson - 1 month ago 12
C++ Question

Displaying An Array big elements

I want to display array using a method, if the array has under 200 elements it display all the elements, which works fine for me. The problem is if the array has over 200 elements i want to display the first 100 elements and the last 100 elements of an array. It works if I use an array of 500 elements or even 10000, but I type something like 9999 or 8999 I get long negative integer numbers on the bottom half of my display list but the top half half works. Any advice?

int main()
{
string fileName,text, size;
fstream inText;
int lengthOf = 0;
cout << "Please Enter An Input File Name: ";
getline(cin, fileName);
inText.open(fileName.c_str() , fstream::in);
if(!inText)
{
cout << "Could Not Open " << fileName << " File" << endl;
exit(EXIT_FAILURE);
}
else
{
inText >> lengthOf;
int * myArray = new int[lengthOf];
for(int i = 0; i < lengthOf; i++)
{
inText >> myArray[i];
}

cout << "Data File Array " << endl;
displayArray(myArray,lengthOf);

}
return 0;
}
void displayArray (int a[], int s)
{
if(s <= 200)
{
for (int i = 0; i < s; ++i)
{
if(i%10 == 0)
{
cout << endl;
}
cout << setw(6) << a[i] << " ";
}
cout << endl;
}
else
{
for(int i = 0; i < 100; i++)
{
if(i%10 == 0)
{
cout << endl;
}
cout << setw(6) << a[i] << " ";
}
cout << endl;
for (int i = s-100; i < s; ++i)
{
if (i%10 == 0)
{
cout << endl;
}
cout << setw(6) << a[i] << " ";
}
cout << endl;
}

}

Answer

Printing the array is straight forward, example:

int main()
{
    int a[551]; //some random number
    int s = 551;
    for (int i = 0; i < s; ++i) a[i] = i;

    for (int i = 0; i < s; ++i)
    {
        if (i % 10 == 0) cout << "\n";
        if (i % 100 == 0) cout << "\n";
        cout << std::setw(6) << a[i] << " ";
    }
    return 0;
}

When reading the file you can use std::vector to store the integers, this way you don't have to know how big the array should be before hand. The example below reads text and then tries to convert to integer, this way you know if there was an error in input file.

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
    std::string fileName;
    cout << "Please Enter An Input File Name: ";
    getline(cin, fileName);
    std::ifstream inText(fileName);
    std::vector<int> vec;
    std::string temp;
    while (inText >> temp)
    {
        try {
            int i = std::stoi(temp);
            vec.push_back(i);
        }
        catch (...) {
            cout << temp << " - error reading integer\n";
        }
    }

    for (size_t i = 0; i < vec.size(); ++i)
    {
        if (i % 10 == 0) cout << "\n";
        if (i % 100 == 0) cout << "\n";
        cout << std::setw(6) << vec[i] << " ";
    }
    return 0;
}
Comments