反转和切换数组中的值C++
reversing and switching values in an array C++
有人可以帮我如何以相反的顺序交换数组 A[10] 和数组 B[10] 中的值吗?这是我到目前为止的代码,另外,如果所需的值是一个数字,我的代码将是什么..不是一封信?
#include <iostream>
#include <iomanip>
using namespace std;
using std::setw;
void REVERSE(char *);
int A, B;
int main()
{
cout << "word in A: " << endl;
cin >> char A[];
cout << "word in B: " << endl;
cin >> char B[];
REVERSE(A);
REVERSE(B);
return 0;
}
void REVERSE (char *A)
{
int counter = 0;
while(A[counter] != ' ')
counter++;
for(int i=counter-1;i>=0;i--)
cout<<A[i];
cout<<endl;
};
if(A>B)
{
temp = A;
A = B;
B = temp;
}
你的代码中有几个错误。
您将A
和B
声明为整数值。但是,您(可能)尝试将它们读取为char[]
(字符数组)。除了这一行cin >> char[] A
应该给你一个编译器错误之外,这甚至没有意义。不能将字符值存储在整数中。
如果您尝试读取字符串或字符数组,请将A
和B
声明为一个。
此外,代码末尾的尾随 if 语句也会让你的编译器抱怨。C++不是脚本语言。如果语句不在函数内部,则不会执行语句。
以下程序执行我认为您尝试的方法:
#include <iostream>
#include <algorithm> // include algorithm to use std::reverse
using namespace std;
int main()
{
string A, B; // declare A and B to be a string, there is no need to declare them at global scope
cout << "word in A: ";
cin >> A;
cout << "word in B: ";
cin >> B;
reverse(A.begin(), A.end()); // reverses A
reverse(B.begin(), B.end()); // reverses B
cout << A << " " << B << endl; // prompt A and B
}
如果要读取整数并将其转换为字符串以反转它们,请尝试以下操作:
#include <iostream>
#include <algorithm> // include algorithm to use std::reverse
using namespace std;
int main()
{
int A, B; // declare A and B to be a int
cout << "word in A: ";
cin >> A;
cout << "word in B: ";
cin >> B;
string strA(to_string(A)); // convert A into a string
string strB(to_string(B)); // convert B into a string
reverse(strA.begin(), strA.end()); // reverses string version of A
reverse(strB.begin(), strB.end()); // reverses string version of B
cout << strA << " " << strB << endl; // prompt strA and strB
}
注意:要使用to_string()
您需要使用 c++11 标准
std::string stringA(A);
std::string stringB(B);
std::reverse(stringA.begin(), stringA.end());
std::reverse(stringB.begin(), stringB.end());
标准::反向 - 反向
int *ptr=&a;
int i=0;
while(i < n-1)
{
ptr++;
i++;
}
i=0;
while(i <n-1)
{
b[i]=*ptr;
ptr--;
i++;
}
希望这有帮助!.如果我正确理解了您的问题,很高兴为您提供进一步的帮助。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '