调用char的函数
Calling a function of char
我是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::vector
的size
方法来获得实际大小。
相关文章:
- 将char*传递给pthread_read函数
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 将函数参数"const char*"转换为"std::string_view"是
- std::string 构造函数如何处理固定大小的 char[]?
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- 构造函数 (C++) 中的 char 指针参数存在问题
- c ++ 如何在构造函数中初始化 char
- 当我尝试通过构造函数分配 char 数组时出现错误
- 将 char 指针传递给接受对 char 数组的引用的函数
- 在字符串函数中抛出'char const*'实例后调用的终止
- 使用 bool 和 const char 重载的 C++ 函数会在没有警告的情况下产生歧义 (MSVC2012)
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- C++函数返回两个 char 数组的相同索引元素
- 为什么const char*和const char[]作为函数参数被认为是等价的
- 为什么 char 数组在从 C++ 中的函数返回时会丢失?
- 如何使用这个原型函数char*encrypt(char*pEncryptedText,const char*pText)
- 仅用于模板化类型的附加构造函数<char>