2013-10-09 37 views
0

在這裏工作是我的代碼:(C++)C++幫助。數組不是整數

#include <iostream> 
#include <stdlib.h> 
using namespace std; 
int main(){ 
    string sentence[9]; 
    string word[9]; 
    inb b[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
    int f = 0; 
    for (int i = 1; i <= 10; i += 1){ 
     cin >> sentence[i - 1]; 
    } 
    for (int a = 10; a > 1; a = a - b[f]){ 
     b[f] = 0;   
     int f = rand() % 10; 
     b[f] = 1; 
     word[f] = sentence[f]; 
     cout << world [f] << endl; 
    } 
} 

然而,當我運行此我得到一個「運行時錯誤」。就是這樣,沒有路線,沒有更多的錯誤。沒有。

如果我在「[]」中使用f,那麼代碼底部的數組,如單詞[f]和b [f]不起作用。

當我用[1]更改所有的「f」來測試代碼時,它可以工作。但是當我使用「f」的時候,它會返回一個運行時錯誤。

不知道這是否是我的編譯器。但是,嘿 - 我是一個2天大的C++編碼器。

+5

'%10'可以返回0到9之間的數字,這意味着總數爲10,但是您的'語句'和'字'數組只有9個元素。 –

+0

學習時的實用提示:如果您想從1開始索引數組,只需將它們設置爲1並且不使用索引0,它可以爲您節省一些頭痛,特別是在實施某些僞代碼時。例如:對於索引爲1..10的數組,有* int arr [11]; //索引0未使用* – hyde

+0

首選''標題。 – chris

回答

2

您的sentence是9「槽」大(地址爲sentence[0]sentence[8])。您嘗試在第10個插槽(sentence[9])中放置某些東西,這是一個不可用的選項。

(重複下面word這種模式。)

您很可能希望宣佈這些陣列爲10元的。

0

這是因爲sentenceword包含九個單位。但rand()%10將產生9,當您使用word[f] = sentence[f]時,單詞[9]和句子[9]超出範圍。 word[9]是數組word的第10個元素。

0

您的代碼有幾個問題。首先,句子和單詞只有9個條目,但你嘗試使用10.數組聲明是基於1的,例如,

char foo [2];

聲明瞭兩個字符。然而,他們被編號爲0和1,從而

char foo[2]; 
foo[0] = 'a'; //valid 
foo[1] = 'b'; //valid 
foo[2] = 'c'; //very bad. 

這個問題可能是你正在「B」自動大小的數組的事實混淆你。

第二個問題是你聲明'f'兩次。

int f = 0; 
for (int i = 1; i <= 10; i += 1){ 

和環路

int f = rand() % 10; 
    b[f] = 1; 

內部你的for循環中,然後,被破壞:

對(INT A = 10;> 1; A = A - B [F] ){

它使用外部'f',它總是0,來訪問b的元素0並從a中減去它。

這裏是我會寫你想要寫代碼:

老實說,我不明白你的代碼是應該做的,但這裏是我如何可能寫的一個簡化版本同樣的事情:

#include <iostream> 
#include <stdlib.h> 
#include <array> 

//using namespace std; <-- don't do this. 

int main(){ 
    std::array<std::string, 10> sentence; // ten strings 

    // populate the array of sentences. 
    for (size_t i = 0; i < sentence.size(); ++i) { // use ++ when ++ is what you mean. 
     std::cin >> sentence[i]; 
    } 

    for (size_t i = 0; i < sentence.size(); ++i) { 
     size_t f = rand() % sentence.size(); // returns a value 0-9 
     std::cout << sentence[f] << " "; 
    } 
    std::cout << std::endl; 
} 

需要C++ 11(-std = C++ 11編譯器選項)。ideone現場演示here