简体   繁体   English

将数组导出到txt文件

[英]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.我有一个代码,它从用户那里接收 3 个数字,然后对它们进行排序并打印出一个排序的数组。 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.我正在尝试将排序后的数字导出到 .txt 文件中,但我得到的只是一些随机数,例如 txt 文件中的“342142464”。 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.但我得到的只是一些随机数,如 txt 文件中的“342142464”。

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).这是您写入文件的唯一内容,这也是 UB(未定义行为),因为此处i的值是n (从前一个循环退出后)。

arr[n] is out of bounds and can be any garbage value, or your program may even terminate. arr[n]越界,可以是任何垃圾值,或者您的程序甚至可能终止。

Solution:解决方案:

Just like you printed your sorted array to the console using cout , do the same thing with ofs :就像您使用cout将排序后的数组打印到控制台一样,对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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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