首页 > 解决方案 > 用虚拟数据填充二维数组和输入表单 txt 文件不起作用

问题描述

嗨,所以我需要用 txt 文件中的值填充像 x 这样的虚拟值的二维数组,如果 file.txt 的数据很少或没有数据,则“x”是用来填充空列的

1 23 3 42 5 63 4 . 5
-2 1 43 95 55 5 43 2 -6
. 2 3 -4 5 43 -4 4 35
82 61 3 5 -5 65 . 2 6

我的C++看起来像这样

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main(){
    ifstream file;
    ofstream newfile;
    string filename;
    string text;
    const int n = 10;
    char x = 'x';
    double A[n][n];


    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            A[i][j] = x;
            cout << A[i][j];
        }
    }
    


    do{
        cout << "Podaj nazwe pliku(wraz z rozszerzeniem): ";
        cin >> filename;
        file.open(filename.c_str());
    }while (!file.is_open());

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            if (!file.eof()){
                getline(file, text);
                A[i][j] = stod(text, 0);
                
                
            }else{
                break;
            }
        }
    }
    file.close();

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
           cout << A[i][j]; 
        }
        cout << endl;
    }
}

当我打印出这个数组时,我得到像 127.77098e-3184 这样的输出我无法复制我的输入,因为它现在没有打印我不知道为什么

标签: c++

解决方案


问题:

  1. 当你使用时,std::getline你取整行而不是取一个数字。
  2. "."不是一个有效的参数,std::stod所以它会抛出一个std::invalid_argument异常。

解决方案:

  1. 改为使用std::ifstream::operator>>
  2. 重新格式化文件并将 更改为"."它应该表示的值(我猜它是 0)。即使在语义上,一个点本身也不代表一个数字。

附加信息:

  1. using namespace std;被认为是一种不好的做法。
  2. newFile变量未使用。
  3. x变量应该是双精度的。
  4. <cmath>头未使用。
  5. 您可以使用std::array.

完整代码:

文件.txt

1 23 3 42 5 63 4 0 5
-2 1 43 95 55 5 43 2 -6
0 2 3 -4 5 43 -4 4 35
82 61 3 5 -5 65 0 2 6

主文件

#include <iostream>
#include <fstream>

int main(){
    std::string filename;
    std::string text;
    constexpr int n = 10;
    double x = -1;
    double A[n][n];

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            A[i][j] = x;
            std::cout << A[i][j] << " ";
        }
        std::cout << std::endl;
    }

    std::ifstream file;
    do{
        std::cout << "Podaj nazwe pliku(wraz z rozszerzeniem): "; //Insert filename.
        std::cin >> filename;
        std::cout << std::endl;
        file.open(filename);
    }while (!file.is_open());

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            if(file >> text){
                A[i][j] = std::stod(text, 0);
            }
            else{
                break;
            }
        }
    }
    file.close();

    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
           std::cout << A[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

推荐阅读