为什么我将数字数据从文本文件导入二维数组的代码不起作用

Why does my code to import numeric data from a text file into a 2D array does not work?

本文关键字:二维数组 导入 代码 不起作用 文件 文本 数字 数据 为什么      更新时间:2023-10-16

文本文件中的数据以0 23 4 23 16。。等等

我想把它存储在一个5*5的静态数组中。但是,当我尝试输出数组时,输出的是一堆乱码的数字,而不是我想要导入的数据。

这是我的代码

#include <iostream>
#include <fstream>
using namespace std;
char A[5][5];
int i = 0, j =0;
int main()
{
  ifstream fin("File.txt");
  if (fin.is_open())
  {
   cout << "The file has been opened successfully" << endl;
    while(!fin.eof())
      {
        for(i = 0 ;  i<5; i++)
        {
            for(j =0; j<5; j++)
            {
               fin.get(A[i][j]);
             }
        }
      }
     }

     return 0; 
  }

假设您的"File.txt"包含:

0 23 45 58 36 5 425 442 4

这些特定的25(5*5)个字符。(是的,空格确实算作字符,在ASCII表中,它实际上是第32个字符)。如果你在上面运行这个功能:

for (size_t i = 0;i<5;++i)
    for(size_t j = 0;j<5;++j)
    {   cout << A[i][j] << setw (4);
        cout << int (A[i][j]) << endl;
    }

您将得到以下输出:

0  48
   32
2  50
3  51
   32
4  52
5  53
   32
5  53
8  56
   32
3  51
6  54
   32
5  53
   32
4  52
2  50
5  53
   32
4  52
4  52
2  50
   32
4  52

写在第一行:与字符串相对应的字符(在File.txt中,如果你检查我放的内容,它在垂直方向上是相同的),在第二行,相关的整数值。我想这可能是你的问题。

我假设您希望逐个输入数据。但是,您正在调用的函数:std::istream& get (char& c)按逐字符取数据

(1) 单个字符从流中提取单个字符。返回字符(第一个签名),或将其设置为参数的值(第二个签名)。

来源:http://www.cplusplus.com/reference/istream/istream/get/

对于输入空白分隔输入,考虑使用正常>>运算符,如下所示:

std::string word;
while (file >> word)
{
    ...
}