#13396: 請問這樣寫是錯在哪裡?


eechiu (eechiu)


#include<iostream>
#include<string>
using namespace std;
int main()
{
int len;
string s,str;
while(cin>>s)
{
len=s.length();
for(int i=0; i<len; i++ )
str[i]==s[len-1-i]; //指定str為s反轉後的結果
if(str==s)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}

(是不是for迴圈那裡有些問題)

 

#13397: Re:請問這樣寫是錯在哪裡?


asnewchien@gmail.com (david)


#include
#include
using namespace std;
int main()
{
int len;
string s,str;
while(cin>>s)
{
len=s.length();
for(int i=0; i<len; i++ )
str[i]==s[len-1-i]; //指定str為s反轉後的結果
if(str==s)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}

(是不是for迴圈那裡有些問題)

 

我沒測試您的 code

底下這行應該不對


str[i]==s[len-1-i];

#13404: Re:請問這樣寫是錯在哪裡?


eechiu (eechiu)


#include
#include
using namespace std;
int main()
{
int len;
string s,str;
while(cin>>s)
{
len=s.length();
for(int i=0; i<len; i++ )
str[i]==s[len-1-i]; //指定str為s反轉後的結果
if(str==s)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}

(是不是for迴圈那裡有些問題)

 

我沒測試您的 code

底下這行應該不對


str[i]==s[len-1-i];

我稍微改了一點,不過好像還是不行

#include<iostream>

#include<string>

using namespace std;

int main()

{

    int len;

    string s,str;

    while(cin>>s)

    {

        len=s.length();

        str[len];

        for(int i=0; i<len; i++ )

            str[i]=s[len-1-i];  //指定str為s反轉後的結果

        if(str==s)

            cout<<"yes"<<endl;

        else

            cout<<"no"<<endl;

    }

    return 0;

}

 

 

#13405: Re:請問這樣寫是錯在哪裡?


mirkat.ee06@g2.nctu.edu.tw (炭烤海苔)


 

我稍微改了一點,不過好像還是不行

#include

#include

using namespace std;

int main()

{

    int len;

    string s,str;

    while(cin>>s)

    {

        len=s.length();

        str[len];

        for(int i=0; i<len; i++ )

            str[i]=s[len-1-i];  //指定str為s反轉後的結果

        if(str==s)

            cout<<"yes"<<endl;

        else

            cout<<"no"<<endl;

    }

    return 0;

}

 

 


我把你的str印出來(cout<< str << endl ; ),是空白的喔

可能跟string的特性有關吧,但我對string還不熟,要請別人補充為什麼會這樣...

 

解決方法有兩種

第一種你再寫一個for迴圈,從0~len-1比較兩字串s和str是否相同

第二種是你乾脆不要設str這個字串了,直接用你第一個迴圈比較s[i]和s[len-1-i]是否相同,這種寫法就可以迴避掉string的特性的問題