简体   繁体   中英

Exporting an array to txt file

I have a code that receives 3 numbers from the user, then sorts them and prints out a sorted array. I'm trying to export the sorted numbers into a .txt file but all I get is some random number like "342142464" in the txt file. I fail to understand what I'm doing wrong.

Any help will be greatly appreciated.

#include <iostream>
#include <fstream>
std::ofstream ofs("sorted_numbers.txt");
using namespace std;

int main()
{
    //array declaration
    int arr[3];
    int n,i,j;
    int temp;

    //total numbers to read
    n = 3;

    //read 3 numbers
    for(i=0;i<n;i++)
    {
        cout<<"Enter number ["<<i+1<<"] ";
        cin>>arr[i];
    }

    //print input numbers
    cout<<"Unsorted Array numbers:"<<endl;
    for(i=0;i<n;i++)
        cout<<arr[i]<<"\t";
    cout<<endl;

    //sorting - ASCENDING ORDER
    for(i=0;i<n;i++)
    {       
        for(j=i+1;j<n;j++)
        {
            if(arr[i]>arr[j])
            {
                temp  =arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }

    //print sorted array numbers
    cout<<"Sorted (Ascending Order) Array numbers:"<<endl;
    for(i=0;i<n;i++)
        cout<<arr[i]<<"\t";
    cout<<endl; 

    ofs << arr[i] << std::endl; 

    return 0;
}

Problem:

but all I get is some random number like "342142464" in the txt file.

ofs << arr[i] << std::endl;

This is the only thing you are writing to your file, which is also a UB (undefined behaviour) because the value of i here is n (after exiting from the previous loop).

arr[n] is out of bounds and can be any garbage value, or your program may even terminate.

Solution:

Just like you printed your sorted array to the console using cout , do the same thing with ofs :

for (i = 0; i < n; ++i)
    ofs << arr[i] << '\t';
ofs << endl;

Or you can do this in that previous loop itself:

for (i = 0; i < n; ++i)
{
    cout << arr[i] << '\t';
    ofs << arr[i] << '\t';
}
cout << endl;
ofs << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM