gpt4 book ai didi

C++:存储文本文件

转载 作者:太空狗 更新时间:2023-10-29 19:39:26 24 4
gpt4 key购买 nike

我写了一个简单的程序(C++),它接受 20 个数字并将它们按升序排序。现在我想将程序中的操作保存在一个像“num.txt”这样的文件中。你能解释一下我应该做什么改变吗?

#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;

int main() {

int x[21], s;
int j,i;

for (int i = 1; i < 21; i++)
{
cout << setw(11) << i << ": ";
cin >> x[i];
}
for (int i = 1; i < 21; i++)
{
for (int j = i+1; j < 21; j++)
{
if (x[j] < x[i])
{
s = x[j];
x[j] = x[i];
x[i] = s;
}
}
}

cout << endl;
for (int i = 1; i < 21; i++)
{
cout << i << ": ";
cout << x[i] << "\t";
if (i % 5 == 0)
{
cout << endl;
}
}
getch();
return 0;
}

我知道这很简单,但我几天前才开始,我是新手。

最佳答案

要将数字输出到文件,您可以使用 std::ofstream对于输出流,并将 cout 替换为您用于流的变量名。

std::ofstream outfile;
outfile.open("num.txt");
for (int i = 1; i < 21; i++)
{
outfile << i << ": ";
outfile << x[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();

您还可以更进一步,添加输入验证并使用标准库中的组件来处理您想要完成的大部分工作。例如,我建议使用 std::vector 而不是将数字存储在数组中反而。您也可以使用 std::sort对数据进行排序而不是自己实现。

#include <vector>       // vector
#include <fstream> // fstream
#include <algorithm> // sort
#include <iostream>

int main()
{
std::vector<int> numbers;

while(numbers.size() != 20)
{
int value;

if(!(std::cin >> value))
{
std::cout << "you must enter a number" << std::endl;
}
else
{
numbers.push_back(value);
}
}

// Do the sort. Pretty easy huh!
std::sort(numbers.begin(), numbers.end());

std::ofstream outfile;
outfile.open("num.txt");
if(outfile.is_open() == false)
{
std::cout << "Unable to open num.txt" << std::endl;
}
else
{
for(size_t i = 0; i < numbers.size(); i++)
{
outfile << i << ": ";
outfile << numbers[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();
}
}

关于C++:存储文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16921056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com