2016-05-21 20 views
1
#include<iostream> 
#include<string.h> 
using namespace std; 
int main() 
{ 
    int n; 
    cin>>n; 
    int x=0; 
    while(n--) 
    { 
     char s[3]; 
     cin>>s; 
     if(strcmp(s,"X++")==0||strcmp(s,"++X")==0) 
     x+=1; 
     else 
     x-=1; 
    } 
    cout<<x; 
} 

if文の中でstrcmp行を削除したときに、ループが正常に機能しました。ループが1回実行した直後に終了するのはなぜですか?

+5

'「X ++」'、あなたのための 'のstd :: STRING'代わりの文字列を使用しないで、なぜあなたはC++を使用しているので、' S'はサイズ4 –

+4

の少なくともでなければならないような文字列を格納します入力。比較はまた、 'if(s ==" X ++ "|| ...' –

答えて

0

πάνταῥεῖが言ったように、の大きさは '\ 0' 文字を格納するためには4でなければなりません。それ以外の場合:

cin >> s; // For example write "X++" 

の範囲外の '\ 0' をであなたの文字列を格納して置きます。

プログラムが2回目にループすると、毎回 ""(空の文字列)が得られるため、プログラムを書き込むことはできません。
これを修正するには、をに置き換えても問題ありません。

注::本当にC++を使いたい場合は、std :: stringを使用することをお勧めします。

#include<iostream> 
#include<string> 
using namespace std; 

int main() 
{ 
    int n; 
    cin >> n; 
    int x = 0; 

    while(n--) 
    { 
     string s; 
     cin >> s; 
     if(s == "X++" || s == "++X") 
      x+=1; 
     else 
      x-=1; 
    } 
    cout << x; 
    return 0; 
} 
関連する問題