2014-02-25 98 views
1

能否幫我解決一下我的代碼中的問題?編譯後可執行文件出錯

程序應該要求用戶輸入狗的名字,並最終打印第三隻狗的名字。當我編譯並執行程序時,它說「它停止工作」,並且Windows問我是否想關閉程序或執行其他操作。

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

main() 
{ 
    string perros[10]; 
    int i; 
    for(i=1; i<11; i++) 
    { 
     cout<<"Introduce el nombre del perro"<<endl<<i; 
     cin>>perros[i]; 

    } 

    cout<<"El nombre del tercer perro es "<<perros[2]; 
    system("pause"); 
} 

回答

1

你應該開始啓動循環從0到9

for(i=0; i<10; i++) 

希望這將消除錯誤...

1

數組索引從零開始;所以你的迴路應

for(i=0; i<10; i++) 

此致嘗試寫入到10個元素的數組的第11元件,破壞存儲器和發動難言混亂。

0

您需要從零開始索引,而不是之一,因爲那是何等的C/C++數組被索引。您將溢出堆棧對象的最大大小。

所以,你會在你原來的代碼修復此問題後寫這樣的事:

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

main() 
{ 
    string perros[10]; 
    int i; 
    for(i=0; i<10; i++) 
    { 
     cout<<"Introduce el nombre del perro"<<endl<<i; 
     cin>>perros[i]; 

    } 

    cout<<"El nombre del tercer perro es "<<perros[2]; 
    system("pause"); 
} 

需要注意的是,你也不要,因爲它的目的是用來使用的for循環。您可以將int i;行合併到for循環中。

但是,一個更智能的C++解決方案是使用標準算法,而不是非常低級別的索引,完全避免了這些問題。

所以,你會寫這樣的事:

#include<iostream> 
#include<cstdlib> 
#include <algorithm> 
using namespace std; 

void readNextString(string str) 
{ 
    cout<<"Introduce el nombre del perro"<<endl; 
    cin >> str; 
} 

main() 
{ 
    string perros[10]; 
    for_each(perros, perros + 10, readNextString); 
    cout<<"El nombre del tercer perro es "<<perros[2]; 
    system("pause"); 
} 
+0

感謝兄弟,我不知道有很多的命令又COS我是個一年級學生哈哈但是,是我糾正了代碼和它的工作真的很好,感謝所有 –

+0

@PacoMeraz:只需使用我粘貼的第二個片段即可。不要使用低級索引,當你真的希望遍歷每個元素而不需要索引。如果你碰巧使用C++ 11,你甚至可以用readNextString函數來取消lambda。 – lpapp