将文件中各行的第21个字符复制到新文件,如果该行没有21个字符,则复制该行的最后一个字符。
while(in.get(achar))
{
int c++;
if(achar=='\n')
{c=0;}
if(c==21)
{
out.put(achar);
}
}
前两个功能我做出来了,可是当该行不足21个字符时复制最后一个字符的功能不知道如何实现,请高手指点
谢谢,我明白你的意图,就是当读到回车的时候进行判断C<=21,然后写入
不过这样会有个BUG ,如果该文件有3行
如 123
456
789
由于第三行并没有回车输入,你只能将3 6 写入文件,也就是说该程序写不了没有回车的一行.
你有什么改进的方法吗?谢谢
貌似这么写不行吧
D:\C++平台控制台程序\ewr.cpp(23) : error C2146: syntax error : missing ',' before identifier 'finish'
D:\C++平台控制台程序\ewr.cpp(25) : error C2146: syntax error : missing ';' before identifier 'found'
D:\C++平台控制台程序\ewr.cpp(25) : error C2065: 'found' : undeclared identifier
有3个错误,程序也没有什么没有定义,可能FOR语句有问题
改了,可是还是算不了没有回车的那一行,以下是原代码,你试一下.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void main()
{
ifstream in;
in.open("c:\\text.txt");
if(!in)
{
cerr<<"\aCan't open the File"<<endl;
exit(100);
}
ofstream out;
out.open("c:\\text1.txt");
if(!out)
{
cerr<<"\aCan't whrte the File"<<endl;
exit(102);
}
bool finish=false;
for(int c=1;!finish;c++)
{
char achar,temp;
static bool found=false;
if(!in.get(achar))finish=true;
if(achar=='\n'||achar==EOF){c=1;found=true;}
if(achar!='\n'&&c<=21&&achar!=EOF)temp=achar;
else
{
if(found){out.put(temp);found=false;}
}
}
}
谢谢了,最近在整文件的问题,今天又遇到一个问题
我写了个文件读取函数,使其读取以下文件
//学号 语文 数学 英语 物理 化学
1234 76 89 97 87 98
2345 77 87 90 76 97
2345 89 65 65 75 86
我用传统的方法
ifstream In;
In>>StuID>>yuwen>>shuxue>>yingyu>>wuli>>huaxue;
以上都是整形变量。
成功读取了文件的内容,但是题目要求每一们的平均分,我立即想到了用数组做,但是当我全定义为数组后,
却发现取不出文件的内容。
两位大哥帮我分析分析该如何写这个函数,谢谢
谢谢wimphy,原来用的是结构体,哈哈,学C++真锻炼思维能力,有问题我还会来问的.