读取字符串的长度,然后反转该字符串

Reading a length of a string, then inverse/reverse the string

本文关键字:字符串 然后 读取      更新时间:2023-10-16

基本上,我已经成功地写下了这篇文章,并且我成功地反转了一个单词!但是,当我试图反转包含2个或更多单词的字符串时,我无法获得输出。有人知道如何解决这个问题,或者知道一些技巧吗?

#include <iostream>
using namespace std;
int main()
{
char words[100];
int x, i;
cout<<"Enter message : ";
cin>>words;
x = strlen(words);
//This two line is used to reverse the string
for(i=x;i>0;i--)
cout<<words[i-1]<<endl;
system("pause");
return 0;
}

问题不在于char array与std::string,而在于输入法。

cin>>words更改为cin.getline(words, sizeof(words), 'n');

我猜这个任务是一个习惯数组的任务,所以坚持使用char数组——否则,是的,std::string是易于使用的方法。

您可以使用std::string代替C字符数组,也可以使用string::reverse_iterator以相反的顺序读取单词。要读取用空格分隔的多个单词,需要使用std::getline。

std::string words;
std::getline(std::cin, words, 'n'); //if you read multiple words separated by space
for (string::reverse_iterator iter = str.rbegin() ; iter != str.rend(); ++iter)
{
std::cout << *iter;
}

或使用std::reverse

std::reverse(words.begin(), words.end());

使用cin.getline(words,99)而不是cin>>words,因为cin>>字将只获得第一个空白处的char数组。

相关文章: