#include "afx.h"
#include "string"
#include "fstream"
#include <iostream>
using namespace std;
int main()
{
float a[2000];
int i=0,line_num;
fstream file;
file.open(_T("text1.txt"),ios::in);
if (!file)
{
cout<<"cannot open\n";
return 0;
}
string str;
while(getline(file,str))
{
file>>a[i];
i++;
}
line_num=i+1;
file.close();
cout<<line_num<<endl;
for (int j=0;j<line_num;j++)
{
cout<<"a["<<j<<"]="<<a[j]<<endl;
}
return 0;
}
#include <iostream> #include <fstream> using namespace std; int main(void) { char txtname[50]; char getCh; const char BR = char(10); //換行 等價于 '\n' unsigned short l = 0; cout<<"請輸入你要察看的文件名(全稱):"; cin>>txtname; fstream myin(txtname, ios::in | ios::binary); if(NULL == myin) { cout<<"打開文件錯誤或沒有該文件,退出。"<<BR; exit(1); } while(myin.get(getCh)) { if(BR == getCh) l++; } myin.close(); cout<<"文件 "<<txtname<<" 有 "<<l<<" 行。"<<endl; return 0; } |
#include "afx.h"
#include "string"
#include "fstream"
using namespace std;
ifstream outfile;
outfile.open(_T("WestPosition.txt"),ios::in);
string s;
int linenum=0;
if (outfile)
{
while (outfile.getline((char *)s.c_str(),16))
{
linenum++;
}
outfile.close();
CString cstr;
cstr.Format(_T("行數(shù)為%d"),linenum);
MessageBox(cstr);
}
else
{
MessageBox(_T("open failed!"));
}
讀取一行文本到rString,遇到回車換行符停止讀取
CStdioFile::ReadString(LPTSTR lpsz, UINT nMax);
讀取一行文本到緩沖區(qū),遇到“0x0D,0x0A”時停止讀取,并且去掉硬回車“0x0D”,保留換行符“0x0A”,在字符串末尾添加“\0”(0x00)。nMax個字符里包含0x00這個字符。分析如下:
1)如果nMax <= 字符數(shù),讀取(nMax-1)個字符 + 0x00
2)如果nMax = 字符數(shù) + 1,讀取nMax個字符 + 0x00
3)如果nMax > 字符數(shù),讀取nMax個字符 + 0x0A + 0x00
CStdioFile::ReadString(CString &rString);(重載)
讀取一行文本到rString,遇到回車換行符停止讀取?;剀嚭蛽Q行符不讀到rString,而且末尾也沒有添加“\0”。