繁体   English   中英

C ++帮助。 数组不适用于整数

[英]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个元素的数组。

这是因为sentenceword包含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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM