调用char的函数

Calling a function of char

本文关键字:函数 char 调用      更新时间:2023-10-16

我是c++编程的新手,我们被告知要编写一个插入排序代码,其中数组是从名为test1.txt的文件中获得的。文件的第一行是数组中的元素数,第二行是数组。我们被要求通过指针从文件读取函数返回数组,但目前我尝试使用int。我编写了以下代码来从文件中获取输入,但我收到了一个错误,说"test1没有在这个范围内声明"。我尝试使用创建test1并写下内容并显示它的代码,效果很好。我想现在使用这个文件。问题出在哪里?我还需要程序下一部分的元素数量,所以我想如果将其用作数组的第一个元素。这样行吗?

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int read_input_array(char* fileName)
{
  string line1;
  string line2;
  std::vector<int> vect;
  ifstream myfile (fileName);
    getline (myfile,line1);
    int value = atoi(line1.c_str());
    cout << "The number of elements is- "<< value << 'n';
    int val = value;
    int array1[val+1];
    array1[1]=value;
    getline (myfile,line2);
    cout <<"The rest is - " << line2<< 'n';
    myfile.close();
    std::stringstream ss(line2);
    int i;
    int j=2;
    while (ss >> i)
    {
        vect.push_back(i);
        if (ss.peek() == ',')
            {ss.ignore();
            cout <<i <<'n';
            array1[j] = i;
            j++;}
    }
    for (int a=1; a<value+1 ;a++)
    {
        cout <<array1[a]<<endl;
    }
  return 0;
}
int main ()
{
    read_input_array( *test1.txt);
    return 0;
}

第一眼,更改:

read_input_array( *test1.txt);
//interpreted as "dereference a pointer called 'txt', which is a member of some object called 'test1', which hasn't been declared".

read_input_array("test1.txt"); //i.e. a string representing the name of the file.

C++中的文字字符串表示为const char* s。

因此,如果在主函数中调用:read_input_array("test1.txt");,那么在read_input_array函数中,fileName将保持值:"test1.txt"。

至于将大小作为数组的第一个元素传递,我建议您只将元素放在std::vector中。然后您可以调用std::vectorsize方法来获得实际大小。