[英]C++ Help. Arrays not working with integers
這是我的代碼:(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,則代碼底部的數組(如word [f]和b [f])將不起作用。
當我用[1]更改所有“ f”以測試代碼時,它可以工作。 但是,當我使用“ f”代替時,它將返回運行時錯誤。
不知道那是我的編譯器。 但是,嘿-我是2天大的C ++編碼器。
您的sentence
大了9個“插槽”(地址為sentence[0]
至sentence[8]
)。 您嘗試在第10個插槽中放入某些內容( sentence[9]
),這是禁止的。
(此模式在下面用word
重復。)
您最有可能希望將這些數組聲明為10個元素的數組。
這是因為sentence
和word
包含9個單位。 但是,當您使用word[f] = sentence[f]
, rand()%10
將產生9
,而word [9]和句子[9]不在范圍內。 word[9]
是數組word
的第十個元素。
您的代碼有幾個問題。 首先,句子和單詞只有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循環已損壞:
for(int a = 10; a> 1; a = a-b [f]){
它使用始終為0的外部“ f”訪問b的元素零,並從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現場演示在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.