c++ - 显示数组大元素

标签 c++

我想使用一种方法显示数组,如果数组的元素少于 200 个,它会显示所有元素,这对我来说很好。问题是如果数组有超过 200 个元素,我想显示数组的前 100 个元素和最后 100 个元素。如果我使用包含 500 个元素甚至 10000 个元素的数组,它会起作用,但我键入类似 9999 或 8999 的内容时,我在显示列表的下半部分得到长负整数,但上半部分有效。有什么建议吗?

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;
   }

}

最佳答案

打印数组很简单,例如:

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;
}

当读取文件时,您可以使用 std::vector 来存储整数,这样您就不必事先知道数组应该有多大。下面的示例读取文本,然后尝试转换为整数,这样您就可以知道输入文件是否有错误。

#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;
}

关于c++ - 显示数组大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195423/

相关文章:

c++ - 如何通过构造函数将容量大小传递给无锁 spsc_queue

c++ - 如何在linux/c++中控制主音量?

android - 使用 cocos2dx (v3.6) 读取写入文件到 android 错误

c++ - ACE vs Boost vs Poco vs wxWidgets

python - 在 C++ 中存储数据,就像在 python 中存储字典一样

c++ - 在 3ds max 中识别平面对象

c++ - Python 最大化一个核心,而 C++ 没有

c++ - 如何使用 std::regex?

c++ - C/C++ 程序的内存布局如何?

c++ - 友元函数出现奇怪的编译器错误