【发布时间】:2013-03-11 22:09:00
【问题描述】:
// 编辑:我发现了我的错误。我仍然缺少一件事:它没有正确计算行数。如果 .txt 中的最后一个字符不是 '\n' ,则它会减少 1 行。如果我击中它,它很重要 2。怎么了 ?你能帮助我吗?
krol.txt =
2 4
3 7
3 13
2 4
3 1
和 main.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(){
ofstream outFile;
ifstream fin;
fin.open("krol.txt");
int l=0;
char ch;
while (fin.good()){
fin.get(ch);
if (ch=='\n') l++;
}
cout << l;
fin.close();
fin.open("krol.txt");
int temp[l][2];
int savel=l;
l=0;
int i=0;
while (fin >> (temp[l][i])){
i++;
if(i==2){
i=0; l++;
}
}
outFile.open("save.txt");
for (int i=0, j=0;j<savel;i++){
if (i==2) {
i=0; j++;
}
outFile << temp[j][i];
}
outFile.close();
system("PAUSE");
return 0;
}
【问题讨论】:
-
禁止将二进制数据写入文本文件。
-
该代码将永远编译。大括号不匹配、未声明等。请发布“真实”代码。
-
哦!我粘贴了错误的代码。对此我很抱歉。现在更正了
-
您正在尝试保存到数组 int temp[l][2] - 它可以包含文件中的 1*2 个整数 5* 2 个整数。你不觉得这很奇怪,你应该调整你的文件或数组的大小。所以在数组的情况下: temp[5][2] - 当然我认为使用硬编码数字是非常糟糕的做法
-
文件必须看起来像 array[x][y] where y - const int y=2;
标签: c++ text-files ifstream ofstream dev-c++