![](/img/trans.png)
[英]I want to convert int to char array where 0-7 bits of int are 1st char 8-15 2nd etc
[英]How to pass char type array to a function and copy 1st char array to 2nd chart array and compare it using c++?
这是我想要的:
声明一个大小为15的字符数组,以存储用户的字符(字符串输入)值。 现在执行以下任务:
这是我的代码
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
void mycopy(char array);
int main(){
//Using Loop to input an Array from user
char array[15];
int i;
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
for (i = 0; i < 15; i++)
{
cin >> array[i];
}
// output each array element's value
cout << "Please Enter your 15 characters" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
cout << setw(7) << j << setw(13) << array[j] << endl;
}
mycopy(array[15]);
return 0;
}
void mycopy(char array[15]) {
char array1[15];
strncpy_s(array1, array, 15);
cout << "The output of the copied Array" << endl;
cout << "**************************************************" << endl;
cout << "Element" << setw(13) << "Value" << endl;
for (int j = 0; j < 15; j++) {
cout << setw(7) << j << setw(13) << array1[j] << endl;
}
}
上面的代码将数组传递给函数Copy()并将第一个数组的值复制到第二个char数组,但是由于传递了无效参数,该代码生成了异常。 当我搜索堆栈溢出时,但没有找到任何类似的问题可以解决我的问题。 提前致谢。
不要使用strncpy_s
,这是非标准的。 相反,请像原来一样使用strncpy
。 为了使用它,您需要包括cstring
。
#include <cstring>
您的原型和mycopy()
定义是不同的。 您的原型需要一个char
但是您的定义需要一个char
数组。 使它们都采用数组。 以下三个中的任何一个都将起作用:
void mycopy(char* array);
void mycopy(char array[]);
void mycopy(char array[15]);
当您在main()
中调用mycopy()
,您尝试访问第15个索引处的数组并将该字符传递给函数。 这是错误的,因为第15个索引超出范围,并且该函数采用了指向char
数组而不是char
的指针。 您只需要将指针传递给数组即可。
mycopy(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.