如何在 c++ 中将数字从文件移动到数组中

How to move numbers from a file into an array in c++

本文关键字:文件 移动 数组 c++ 数字      更新时间:2023-10-16

我在调用我创建的名为"numbers.txt"的文件中的数据时遇到问题。该文件具有数字 1-26,应该放在一个数组中。现在它没有编译。我有类似的项目,没有问题。所以我不知道我做错了什么。下面是我正在使用的代码。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototypes:
int readEncodingCipher(string filename, int encodeKey[], int size);
int main()
{
    string fileName;
    const int size = 26;
    int encodeKey[size];
    //Requests the name of a file to read from.
    cout << "Please enter a file name with a key: ";
    cin >> fileName;
    readEncodingCipher(fileName, encodeKey, size);
    system("pause");
    return 0;
}
int readEncodingCipher(string fileName, int encodeKey[], int size)
{
    string fileName;
    ifstream inFile;
    int num;
    int counter = 0;
    inFile.open(fileName);
    if (inFile)
    {
        while (inFile >> num && counter <= size)
        {
            encodeKey[counter] = num;
            counter++;
        }
    }
    else
    {
        cout << "unable to locate file";
    }
    inFile.close();
}

我假设您收到错误消息

error: declaration of 'std::__cxx11::string fileName' shadows a parameter

在你函数中

int readEncodingCipher(string fileName, int encodeKey[], int size)
{
    string fileName;

局部变量fileName遮蔽参数filename。您必须更改变量名称。修复此错误后,它会为我编译。

此外,还应修复函数的返回类型。将其更改为void或返回一个值。

您应该修复 while 循环的计数器。最后一个元素是 encodeKey[size - 1] ,所以 while 循环应该在这个元素处停止。