可以怎么修改呢?
时间: 2023-10-10 10:04:31 浏览: 54
可以对代码做出以下修改:
1. 在读取文件的循环前,添加一行代码来计算文件中行数n:
```
n = (int)myfile.GetLength() / 100; // 假设每行数据的平均长度为100个字符
```
这样就可以保证读取到所有的数据了。
2. 在读取文件的循环中,将str.GetBuffer(0)改为str.GetBuffer(), 以获取可修改的字符数组指针,然后在调用完strtok()函数后,添加一行代码释放该指针:
```
char* pBuf = str.GetBuffer();
ftemp = strtok(pBuf, " ");
fid = strtok(NULL, " ");
str.ReleaseBuffer();
```
这样就可以正确地按空格分割一行数据了。
3. 在排序时,添加判断字符串是否合法的代码:
```
if (IsStringValid(sort_id.GetAt(j)) && IsStringValid(sort_id.GetAt(j + 1)))
{
double pa = _tstof(sort_id.GetAt(j));
double pb = _tstof(sort_id.GetAt(j + 1));
if (pb < pa)
{
temp_big = sum.GetAt(j);
sum.SetAtGrow(j, sum.GetAt(j + 1));
sum.SetAtGrow(j + 1, temp_big);
CString temp_id = sort_id.GetAt(j);
sort_id.SetAt(j, sort_id.GetAt(j + 1));
sort_id.SetAt(j + 1, temp_id);
}
}
```
其中,IsStringValid()函数用于判断字符串是否合法:
```
bool IsStringValid(const CString& str)
{
if (str.IsEmpty())
return false;
for (int i = 0; i < str.GetLength(); i++)
{
if (!isdigit(str[i]) && str[i] != '.')
return false;
}
return true;
}
```
这样就可以避免字符串转换成浮点数时出错了。
4. 在写入文件时,每行数据的末尾添加一个"\r\n":
```
myfile.WriteString(sum.GetAt(i));
myfile.WriteString("\r\n");
```
这样就可以在Windows系统下正确显示文件内容了。
5. 在打开文件时,使用完整的文件路径:
```
myfile.Open(_T("C:\\path\\to\\book.txt"), CFile::modeRead);
...
myfile.Open(_T("C:\\path\\to\\book.txt"), CFile::modeWrite | CFile::modeCreate | CFile::typeText);
```
这样就可以确保能够正确打开文件了。