我正在解决一个问题,该问题包括获取一行文本并将其向后翻转。例如,我输入 Welcome 并输出 emocleW。
问题是我的代码部分有效,一半的线向后转,但另一半则不然,它保持好像我没有碰它一样。输出看起来像 emocom,输入为 Welcome
这可能是一个愚蠢的问题,但我是新人,我不知道该怎么办了。
如果我的英语有点奇怪,我也很抱歉,我不是母语人士。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <map>
#include <algorithm>
using namespace std;
int main(){
string line;
cin >> line;
int c=0;
for (auto &&i : line)
{
c++; // Here i take the lenght of the line and save it in c
}
for (int chara = 0; chara < c; chara++) // I use this for iterating all the chars in my string
{
line[chara] = line[c-chara-1]; // Here i try to swap the chars by putting the value of // the greatest index in the place 0 and so on.
}
cout << line;
return 0;
}
我也尝试过这样做
for (int chara = 0; chara < c; chara++)
{
l = c-chara-1;
line[chara] = line[l]
}
或
for (int chara = 0; chara < c; chara++)
{
l = line[c-chara-1];
}
但没有任何效果。帮助:c
听着,“line[chara] = line[c-chara-1];”...这段代码将完全改变你的字符串,因为你只是改变了字符串的第一部分而不保存它。你可以使用交换(line[chara], line[c-chara-1]) 或者你可以使 temp = line[chara];行[chara] = 行[c-chara-1];行[c-chara-1]=临时; 。我希望你现在明白你犯了什么错误。您也可以使用 line.length() 来获取它的长度。