C++ :字符串反转不起作用
C++ :String reversal not working?
我无法理解这段代码的输出
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
int i = 0;
int j = 0;
int k = 0;
char ch[2][14];
char re[2][14];
cout << "nEnter 1st string n";
cin.getline(ch[0], 14);
cout << "nEnter the 2nd stringn";
cin.getline(ch[1], 14);
for(i = 0; i < 2; i++) {
int len = strlen(ch[i]);
for(j = 0, k = len - 1; j < len; j++, k--) {
re[i][j]=ch[i][k];
}
}
cout << "nReversed strings are n";
cout << re[0];
cout << endl << re[1] << endl;
return 0;
}
例如
/*
Input :
hello
world
Output :
olleh<some garbage value>dlrow
dlrow
*/
对不起,如果它很基本,但我不明白原因。提前谢谢。
确保 re[0]
和 re[1]
以 null 结尾
例如,在初始化期间,您可以执行
for (int i = 0; i < 14; i++)
{
re[0][i] = ' ';
re[1][i] = ' ';
}
但除此之外,我建议使用std::string
和std::reverse
等。
for (i = 0; i < 2; i++)
{
int len = strlen(ch[i]);
for (j = 0, k = len - 1; j < len; j++, k--)
{
re[i][j] = ch[i][k];
}
re[i][len] = ' ';
}
你必须终止你的反转字符串。
此外,您还应该#include <string.h>
strlen()
功能。
您忘记了数组 re
中字符串的终止零 只需按以下方式定义数组
char ch[2][14] , re[2][14] = {};
^^^^
还要考虑到您应该删除标头<stdio.h>
因为它未被使用,而不是包含标头<cstring>
。
可以使用标准算法完成此任务std::reverse_copy
例如
#include <iostream>
#include <algorithm>
#include <cstring>
int main()
{
const size_t N = 2;
const size_t M = 14;
char ch[N][M] = {};
char re[N][M] = {};
std::cout << "nEnter 1st string: ";
std::cin.getline( ch[0], M );
std::cout << "nEnter the 2nd string: ";
std::cin.getline( ch[1], M );
std::cout << std::endl;
for ( size_t i = 0; i < N; i++ )
{
std::reverse_copy( ch[i], ch[i] + std::strlen( ch[i] ) , re[i] );
}
for ( const auto &s : re ) std::cout << s << std::endl;
return 0;
}
相关文章:
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- boost::spirit::x3 中的简单字符串解析器不起作用
- 用于拆分空格字符串的程序不起作用
- 比较字符串的 GetLine 工作一次,然后比较之后不起作用
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- 将字符从一个字符串简单分配到另一个字符串不起作用
- C++ 对象数组字符串输入在控制台上不起作用
- 字符串代码不起作用
- 检查字符串中的小写字符或空格.布尔值不起作用
- 在C 中使用Atof将字符串转换为小数不起作用
- 字符串等于不起作用 C++
- 从中间器转换字符串不起作用,出了什么问题?
- 为什么strcpy()不起作用,请接受字符串作为参数
- 在字符串中找到元音不起作用
- C++将字符串写入文本文件中的行;新行问题不起作用
- int 有效,但字符串::size_type不起作用
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- C++字符串不起作用
- 排序功能不起作用(字符串比较问题)