【发布时间】:2018-03-30 19:15:20
【问题描述】:
对不起,如果这是一个愚蠢的问题,但我是一个学习 C++ 的新手程序员。
我有一个作业,其中为输入 txt 文件提供了 16 行 1-5 位数字,每行最多 5 个数字。我们应该写一个函数 findmax 在 main 中使用,将每行中的最大数字输出到另一个 txt 文件中。
我的代码没有当前的编译错误我只是停留在如何在 main 中实际使用此函数并将其传递到输出文件中。如果这真的很简单,再次抱歉。
#include <iostream>
#include<fstream>
using namespace std;
int *make( int n)
{
#if 0
int *a = new int[n];
#else
int a[n];
#endif
for( int i=0; i < n; ++i) a[i] = i;
return a;
}
int findmax(int x1,int x2,int x3,int x4, int x5)
{
for(int i=0;i<5;i++)
{
int n, temp;
int a[i];
if(a[i]>temp)
temp=a[i];
return temp;
}
}
int main()
{
int n;
int x1, x2, x3, x4, x5, y1, y2, y3, y4, y5;
cout << "Enter number of lines n in the input file." << endl;
cin >> n;
int *a = make(n);
for( int i = 0; i < n; ++i) cout << a[i] << " "; cout << endl;
ifstream infile; infile.open("/home/labs/lab4/lab4_input.txt");
ofstream outfile; outfile.open("/home/labs/lab4/lab4_output.txt");
if( !infile.is_open()) cout << "open infile failed\n";
infile >> x1 >> x2 >> x3 >> x4 >> x5;
findmax( x1, x2, x3, x4, x5);
outfile << y1 << " " << y2 << " " << y3 << " " << y4 << " " << y5 << endl;
infile.close();
outfile.close();
return 0;
}
【问题讨论】:
-
您需要打开您的 C++ 教科书并阅读有关数组的章节。这个网站不能教你这样的基本概念。您的程序完全是偶然编译的(因为您使用了错误的编译标志)。
-
在您的
make函数中,int a[n];创建一个不属于标准 C++ 语言的可变长度数组 (VLA)。在网上搜索“c++ 数组动态内存新”。 -
使用 std::vector!
标签: c++ arrays pointers dynamic