加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

阅读数字列表并排序C.

发布时间:2020-12-16 10:22:03 所属栏目:百科 来源:网络整理
导读:我正在尝试从文件中读取数字列表,并通过将它们读入数组然后对数组内容进行排序来对它们进行排序.但我得到了 error:incompatible types in assignment of 'std::basic_ostreamchar,std::char_traitschar ' to 'int [1]' 我对编程很新,这是我第一次使用C语言
我正在尝试从文件中读取数字列表,并通过将它们读入数组然后对数组内容进行排序来对它们进行排序.但我得到了

error:incompatible types in assignment of 'std::basic_ostream<char,std::char_traits<char> >' to 'int [1]'

我对编程很新,这是我第一次使用C语言
谁能告诉我如何将数字列表写入数组,以便我可以对它们进行排序?
这是我有的:

#include <fstream>
#include <iostream>
#include <iomanip>
#define ANYSIZE_ARRAY 1
using std::cout;
using std::endl;


int main()
{
  const char* filename = "test.txt";
  std::ifstream inputFile(filename);
  int numbers[ANYSIZE_ARRAY];
  int i,key;

  // Make sure the file exists
  if(!inputFile)
  {
    cout << endl << "The File is corrupt or does not exist. " << filename;
    return 1;
  }

  long n = 0;
  while(!inputFile.eof())
  {
    inputFile >> n;
    numbers = cout << std::setw(10) << n;
  }

  for(int j=1;j<5;j++)
    {
        i=j-1;
        key=numbers[j];
        while(i>=0 && numbers[i]>key)
        {
                    numbers[i+1]=numbers[i];
                    i--;
        }
        numbers[i+1]=key;
    }

    //Display sorted array
    cout<<endl<<"Sorted Arrayt";
     for(i=0;i<5;i++)
       cout<<numbers[i]<<"t";
    cout<<endl;
}

解决方法

导致错误的行是:

numbers = cout << std::setw(10) << n;

我不太确定你在这里尝试做什么,看起来你只想打印它,在这种情况下数字=不需要.

用于读取所有数据的循环结构也存在问题.行:while(!inputFile.eof())不是惯用的C,也不会做你想要的. See here for a discussion on that issue(和here).

作为参考,您可以通过使用std :: sort来减少工作量

#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>

int main() {
  std::ifstream in("test.txt");
  // Skip checking it

  std::vector<int> numbers;

  // Read all the ints from in:
  std::copy(std::istream_iterator<int>(in),std::istream_iterator<int>(),std::back_inserter(numbers));

  // Sort the vector:
  std::sort(numbers.begin(),numbers.end());

  // Print the vector with tab separators: 
  std::copy(numbers.begin(),numbers.end(),std::ostream_iterator<int>(std::cout,"t"));
  std::cout << std::endl;
}

这个程序还使用std :: vector而不是数组来抽象“我的数组应该有多大?”问题(你的例子看起来可能存在问题).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读