有人可以向我解释一下这个程序吗?

时间:2016-12-02 04:21:38

标签: c++ arrays reverse

下面有一个程序。我不明白它是如何反转char数组的。我的意思是它工作正常,它确实反转了用户存储在char数组中的字符串,但我想知道它是如何工作的以及它如何逆转顺序?基本上我不理解第一个for循环,它在正文中没有任何语句加上for循环的第一部分缺失。请用简单易懂的词语解释,而不是用典型或难懂的词语。我不是母语为英语的人。非常感谢。

#include <iostream>
using namespace std;

int main()
{
    char name[99];
    int counter=0;

    cin >> name;

    for(;name[counter]!='\0'; counter++)
    {}

    cout << "\nName: ";

    for (;counter > 0; counter--)
    {
        cout << name[counter-1];
    }
}

4 个答案:

答案 0 :(得分:0)

C字符串为空('\ 0')终止。第一个循环递增counter,直到找到name中包含的字符串的末尾。这由空字符表示。重要的一点是counter在第一个for循环之外被声明,并且它在第二个循环执行时保持在范围内,并且具有相同的值。第二个循环然后从name中的字符串末尾开始打印字符,直到它打印出第一个字符。

答案 1 :(得分:0)

In Your Program, First For loop is to know number of characters in name variable. Let me explain you how it works.
For loop have basic structure like
for(i=10;i>0;i--)
{
//Body part of for
}
First part i=0 is initialization, second part is condition and third part is Increment/Decrements.
In your program, We have already initialize value of counter as 0.
This loop is just for counting number of characters so after every loop count variable will increment. We do not need to write anything in body part.

after completing first for loop count variable have same value as name variable's characters.
Again in second loop we don't need to initialize count values because count already have some value stored in it.

Hope You understand now..!!

答案 2 :(得分:-1)

you start your counter at 0.

for(;name[counter]!='\0'; counter++){} 

the for loop above increments the counter until it reaches '\0' .At this point your counter has incremented to the number of characters of what you typed as name. eg: if you typed hello counter is now at 5.

for (;counter > 0; counter--){cout << name[counter-1]; }

In the above for loop,you start by having the counter value at 5 then printing out each character of your array in reverse because first iteration your counter is 5, you print name[4] which is o then counter decrements so you print name[3]=l,then name[2]=l, then name[1]=e , then name[0] =h. Note: if your counter is at value n you are printing n-1. so when your counter decrements to 1 you print name[0]. then the counter finally decrements to 0 where the loop becomes false. Also you are not reversing the array elements themselves but are just printing them in reverse.

答案 3 :(得分:-1)

select t.Complaint_id,t.text_note,i.Photo_link,a.audio_link
from text t 
left join image i on t.compalint_id=i.complaint_id 
left join audio a on t.compalint_id=a.complaint_id