【问题标题】:Copy .txt to int array, then save into another file将 .txt 复制到 int 数组,然后保存到另一个文件中
【发布时间】: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++


【解决方案1】:

我不是 C++ 专家,但不应该

fout >> ch;

fout << ch; 

?

(根据 Thomas Matthews 的评论修正)

【讨论】:

  • 其实 `fin >> ch' 可能就是他的意思吧?
  • 我在粘贴错误代码时犯了错误(未更正)。现在我将其编辑为可编译的代码。
  • 如果它的输出是fout &lt;&lt; ch;
猜你喜欢
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
相关资源
最近更新 更多