循环向后打印字符串

时间:2012-11-01 21:27:53

标签: c++ string

程序会询问用户一系列字符串(他们的名字和一个8个字母的单词),打印他们的名字,单词的第一个和最后三个字母,然后向后打印他们的单词。需要帮助for循环向后显示字符串。

    #include <iostream> 

int main () { 


string FirstName; 

string LastName; 

string MiddleName; 

string Names; 

string string1; 

int len; 

int x;  

 cout << "Hello. What is your first name?" << endl; 

 cin >> FirstName; 

 cout << FirstName  << ", what is your last name?" << endl; 

 cin >> LastName; 

 cout << "And your middle name?" << endl; 

 cin >> MiddleName; 

 Names = LastName + ", " + FirstName + ", " + MiddleName; 

 cout << Names << endl; 

 cout << "Please enter a word with 8 or more characters (no spaces): " << endl; 

 cin >> string1; 

 len = string1.length(); 

   if (len < 8){
     cout << "Error. Please enter a word with 8 or more characters and no spaces: " <<    endl; 

     cin >> string1; 
 }

  else if (len >= 8){

     cout << "The word you entered has " << string1.length() << " characters."<<endl; 

 cout << "The first three characters are " << string1.substr(0,3) << endl; 

 cout << "The last three characters are " <<string1.substr(string1.length()-3,3) << endl; 

x = string1.length()-1; 

for (x = string1.length()-1; x >=0; x--){
 cout << "Your word backwards: " << string1[x]; 
}
}



return 0; 
} 

4 个答案:

答案 0 :(得分:4)

你快到了那里:

cout << "Your word backwards: ";
for (x = string1.length()-1; x >=0; x--){
   cout << string1[x]; 
}

这样循环将打印string1中的每个字符,但顺序相反,文本"Your word backwards: "只打印一次。

答案 1 :(得分:1)

如果你想要幻想:

copy(string1.rbegin(), string1.rend(), ostream_iterator<char>(cout));

答案 2 :(得分:0)

简单的方法是从后面将字符串存储在临时数组中,然后使用此临时数组来打印反向字符串。 例如: - temp [j - ] = str [i ++];在一个循环中。 但在此之前要小心,将数组'temp'的大小初始化为原始数组的大小。在这种情况下'str'在这里。

答案 3 :(得分:0)

这可能不是你问题的答案,但我选择其中一个:

std::cout << "Your word backwards: "
          << std::string(string1.rbegin(), string1.rend()) << '\n';

*std::copy(string1.rbegin(), string1.rend(),
           std::ostreambuf_iterator<char>(std::cout << "Your word backwards: "))++ = '\n';

std::reverse(string1.begin(), string1.end());
std::cout << "Your word backwards: " << string1 << '\n';