簡體   English   中英

使用循環向后C ++打印一個char數組

[英]printing a char array backwards c++ using loops

我試圖向后打印一個未知長度的數組,所以寫了循環應該從終止符開始,並轉到第一個字母,以打印每個字母,但它只打印第一個字母

#include <iostream>
using namespace std;

int main()
{
    char word[10];
    int i;

    cout << "Enter a word: " ;
    cin >> word;

    for ( word[i]= '\0'; word[1] <0; word[i] --)
    {
        cout << word[i] << endl;

    }
    return 0;
}

您可以使用此單行代碼向后打印C樣式的字符串:

reverse_copy(word,word+strlen(word),ostream_iterator<char>(cout));

另外考慮使用std::string

string word;
cin >> word;

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

您需要#include以下標頭才能使上述示例起作用:

<algorithm>, <iostream>, <iterator>, <string> and <cstring>

替換循環無用:

for (i= strlen(word); i >=0; i--)
    {
        cout << word[i] << endl;  //endl is optional

    }

同樣對於長字符串,您可能必須增加char數組的大小或更好地使用它

string word;
for (i= word.size(); i >=0; i--)
        {
            cout << word[i] << endl;  //endl is optional

        }

這是向后打印C樣式字符串的簡單方法。

for (size_t i = 0, i_end = std::strlen(word); i != i_end; ++i)
{
    std::cout << word[i_end - i - 1];
}
std::cout << "\n";

請注意,我保存了strlen的結果,因此不會每次都調用它。

為了獲得想要的結果,您可能想要使用此代碼...

char word[10];
int sz; 

do {
    cout << "Enter a word: ";
    cin >> word;
    sz = strlen(word);

} while (sz > 10);


for (int i = sz; i >= 0; i--)
{
    cout << word[i];

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM