编写一个控制台程序,打开一个txt文件,输入20个整数,通过数组编程的方式,对其从小到大排序,将排序的结果保存到“result.txt”中。

qq_38621067 2017-08-11 10:31:02
这个程序有问题,求大神帮帮忙啊
#include "stdafx.h"
#include "iostream.h"
#include "string.h"
#include "math.h"
#include <stdio.h>
#include <stdlib.h>
#include "fstream.h"
//using namespace std;

#define M20

int main(int argc, char* argv[])
{
fstream file1; // 定义一个fstream类的对象用于读
file1.open("1.txt", ios::in);
if (!file1)
{
cout<<"1.txt不能打开!\n";
return 1;
}
fstream file2; // 定义一个fstream类的对象用于写
file2.open("result.txt", ios::out | ios::trunc);
if (!file2)
{
cout<<"result.txt不能创建!\n";
file1.close();
return 1;
}
int k=0;
char ch;
int a[M];
while (!file1.eof())
{
file1.read(&ch, 1);
cout<<ch;
int atoi(const char *nptr);
for(int k=0;k<20;k++)
{
a[k]=atoi(&ch);

}
}
cout<<a[k]<<endl;
int max;
for (int i=0; i<M-1; i++)
{ // 外循环
max = a[i]; k = i;
for (int j=i+1; j<M; j++)
{ // 内循环
if (max<a[j])
{ max = a[j]; k = j; }
}
a[k] = a[i]; a[i] = max;
}
char str[M];
for(int u=0;u<M;u++)
{
sprintf(&str[u],"%d",a[u]); //sprintf函数
}
str[u]='\0';
cout<<str<<endl;
for(int q=0;q<M;q++)
{
cout<<str[q]<<endl;
file2.write(&str[q],1);
}
file2.close(); // 不要忘记文件使用结束后要及时关闭
file1.close();
return 0;
}
...全文
622 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_38621067 2017-08-12
  • 打赏
  • 举报
回复
好的,我试一下
kuangbao9 2017-08-12
  • 打赏
  • 举报
回复
引用 2 楼 qq_38621067 的回复:
int atoi(const char *nptr)怎么头文件,老是出错,,如果不用atoi函数转换的话,大神有没有其他的函数推荐啊
引用 2 楼 qq_38621067 的回复:
int atoi(const char *nptr)怎么头文件,老是出错,,如果不用atoi函数转换的话,大神有没有其他的函数推荐啊
char str[]="1234321"; int a; sscanf(str,"%d",&a); ............. char str[]="123.321"; double a; sscanf(str,"%lf",&a); ............. char str[]="AF"; int a; sscanf(str,"%x",&a); //16进制转换成10进制 另外也可以使用atoi(),atol(),atof().
qq_38621067 2017-08-12
  • 打赏
  • 举报
回复
int atoi(const char *nptr)怎么头文件,老是出错,,如果不用atoi函数转换的话,大神有没有其他的函数推荐啊
kuangbao9 2017-08-12
  • 打赏
  • 举报
回复
while (!file1.eof()) { file1.read(&ch, 1); cout<<ch; int atoi(const char *nptr); for(int k=0;k<20;k++) { a[k]=atoi(&ch); } 这里是不是就有问题了? 读是一个一个字符读的,如果1.txt里面存有2位数,那么那是算两个字符的,这样的话20个a数组空间是不够的,会溢出吧。。。 你这里面的for循环意思不就是把最后一个数字保存下来嘛。。。。。 int atoi(const char *nptr);这个函数啥意思?不是本来就有的库函数嘛。。。

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧