2012-12-04 65 views
0

基本上,我已经设法写出这个,并且设法颠倒了一个单词!但是当我尝试颠倒一个包含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; 
} 
+0

为什么你使用C字符串,如果它应该是一个C++作业? –

+1

为什么不使用'string'?将'char words [100]'改为'string words'并将'x = strlen(words)'改为'x = words.length()' – Maroun

+2

此外,'cin >> words'将停止解析第一个空白字符。你需要使用像getline()这样的东西。 – Angew

回答

1

你可以使用std::string而不是C字符数组,也可以用字符串:: 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()); 
+0

你的代码中的问题是int,cin操作符>>只从流中读取一个单词。 –

2

的问题是不与字符数组VS的std :: string - 它是与输入方法。

变化cin>>wordscin.getline(words, sizeof(words), '\n');

我猜这个任务的分配习惯阵列,所以用字符数组坚持 - 否则,是的,的std :: string是去简单易用的方式。

+0

老兄,谢谢!你是一个救生员。我的讲师从来没有想过我这个“getline”的东西。不管怎么说,还是要谢谢你! – user1874983

0

使用cin.getline(words,99) insted cin>>words,因为cin >>字将只获得字符数组到第一个空格。