亲朋字符串, 求给定字符串 s 的亲朋字符串 s1
s1定义如下:给定字符串 s 的第一个字符的 ASCII 值加第二个字符的 \text{ASCIIASCII 值,得到第一个亲朋字符;给定字符串 s 的第二个字符的 ASCII 值加第三个字符的 ASCII 值,得到第二个亲朋字符;依此类推,直到给定字符串 s 的倒数第二个字符。亲朋字符串的最后一个字符由给定字符串 s 的最后一个字符 ASCII 值加 s 的第一个字符的 ASCII 值。
题目链接见:https://nanti.jisuanke.com/t/T1107
我的代码为什么错,
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string s;
string ans = "";
getline(cin, s);
int length = s.size();
s[length] = s[0];
/*
cout << "ASCLL:" << endl;
for(int i = 40; i < 130; i++)
{
cout << i << "->" << char(i) << endl;
}
cout << "----------" << endl;
cout << int('4') << endl;
cout << int('5') << endl;
cout << char(int('4') + int('5')) << endl;
cout << "----------" << endl;
*/
for(int i = 0; i < length; i++)
ans[i] = s[i] + s[i+1];
for(int i = 0; i < length; i++)
cout << ans[i];
cout << endl;
return 0;
}
错误信息:(答案错误,不是编译错)
已通过 3 组测试数据,共 20 组。
求源代码。
采纳
// Q1052492.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stdlib.h>
using namespace std;
int main()
{
char s[102];
char ans[102];
scanf("%[^\n]", s);
int length = strlen(s);
ans[length] = '\0';
/*
cout << "ASCLL:" << endl;
for(int i = 40; i < 130; i++)
{
cout << i << "->" << char(i) << endl;
}
cout << "----------" << endl;
cout << int('4') << endl;
cout << int('5') << endl;
cout << char(int('4') + int('5')) << endl;
cout << "----------" << endl;
*/
for(int i = 0; i < length - 1; i++)
ans[i] = s[i] + s[i+1];
ans[length - 1] = s[0] + s[length - 1];
for(int i = 0; i < length; i++)
cout << ans[i];
cout << endl;
return 0;
}
std::string::operator[]
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
注意:
If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).
参考
http://www.cplusplus.com/reference/string/string/operator[]/ http://www.cplusplus.com/reference/string/string/operator%5B%5D/