我有txt文件,内容是:
1 (12,23) (23,24) (33,55)
2 (44,55) (27,76) (43,23)
我要把括号里的每个数字,分别存到我的数组中。不要保存序号、空格和括号。怎么读取呢?
------解决方案--------------------------------------------------------
sscanf
------解决方案--------------------------------------------------------
读入一行,然后找到所有的"("、")"、","的位置,使用CString的:
- C/C++ code
// return nCount characters starting at zero-based nFirstCString Mid(int nFirst, int nCount) const;// return all characters starting at zero-based nFirstCString Mid(int nFirst) const;
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
使用CFile读取进来,用mid函数切割。
------解决方案--------------------------------------------------------
- C/C++ code
int a1,a2,a3,a4,a5,a6,a7;while(file.ReadString(str))//按行读取 { if(sscanf(str.GetBuffer(),"%d (%d,%d) (%d,%d) (%d,%d)",&a1,&a2,&a3,&a4,&a5,&a6,&a7)==7) { //a2,a3,a4,a5,a6,a7 } }
------解决方案--------------------------------------------------------
看例子:
CStdioFile fileR;
if( !fileR.Open(_T("your.txt"),CFile::modeRead|CFile::shareExclusive|CFile::typeText) )
{
AfxMessageBox(_T("读文件出错!") );
return;
}
int iPositionL,iPositionR,iDot;
CString SReadStr,SPositionL,SPositionR,STemp;
//我有txt文件,内容是:
//1 (12,23) (23,24) (33,55)
//2 (44,55) (27,76) (43,23)
while(fileR.ReadString(SReadStr))//SReadStr : 1 (12,23) (23,24) (33,55)
{
iPositionL = -1;
while( (iPositionL = SReadStr.Find ( '(',iPositionL + 1 ) ) != -1 )
{
iPositionR = SReadStr.Find ( ')',iPositionL );
STemp = SReadStr.Mid ( iPositionL + 1, iPositionR - iPositionL - 1 );
//STemp : 12,23
iDot = STemp.Find ( ',' );
SPositionL = STemp.Left ( iDot );// SPositionL : 12
SPositionR = STemp.Mid ( iDot + 1 );// SPositionR : 23
}
}
附注,下面是将字符串转整数例子:
char* Str;
USES_CONVERSION;
Str = T2A( SPositionL.GetBuffer() );//系统宏T2A(W2A)
int iTemp = atoi( Str );