首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

从文件读入一组数到待排序数组的函数用来被排序算法调用,本人很菜请指出异常的同时给出代码

2012-02-25 
从文件读入一组数到待排序数组的函数用来被排序算法调用,本人很菜请指出错误的同时给出代码C/C++ code#inc

从文件读入一组数到待排序数组的函数用来被排序算法调用,本人很菜请指出错误的同时给出代码

C/C++ code
#include<iostream>#include<fstream>#include<stdlib.h>#include<stdio.h>#define LEN 10void getarray(int* array,int n){    int index=0;    FILE *fp = fopen("data.txt","r");    if(0==fp)        return;    while(!feof(fp)&&index<n)    {        fscanf(fp,"%d,",&array[index]);        ++index;    }}void BubbleSort(int a[],int n){    int i,j,temp;    for(j=0;j<n-1;j++)    {        for(i=0;i<n-j-1;i++)        {            if(a[i]>a[i+1])            {                temp=a[i+1];                a[i+1]=a[i];                a[i]=temp;            }        }    }}int main(){    int array[10];    getarray(array,10);    //int a[10]={2,4,6,3,7,9,8,10,1,5};    BubbleSort(array,10);    for(int i=0;i<10;i++)    {        cout<<array[i]<<"\t";    }    return 0;}            


文本文件内容为:1 2 4 3 6 5 7 9 8 0
这段代码输出结果怪异是不相干的10个负数
错误我知道是getarray()的,排序算法没有错
请问怎么做

[解决办法]
C/C++ code
inFile("data.txt");if(inFile==0) return 0;int i=0;while(i<n)   inFile>>array[i++];试一下,手头没有编译器,
[解决办法]
fscanf(fp,"%d,",&array[index]);
有逗号的话,文件内各数据之间须用逗号隔开,
而你的文件中没有逗号..

热点排行
Bad Request.