无法在C ++中索引矩阵?

Sunnykevin

C ++的新手,我正在提供矩阵索引作为用户输入。无法运行该脚本。建议!

#include<iostream>
using namespace std;
int main()
{
    string fools[3][4] = {{"cat","dog","mon","junk"},
                          {"dad","mom","sis","fath"},
                          {"fox","cow","buff","chip"}};
for(int i=0; i < 3;i++)
        {
        for(int j=0; j< 4;j++)
        {
        cout << fools[i][j]<< " " << flush;
        }
        cout << endl;
        }
    cout << "Enter the matrix index:" <<flush;
    int num1,num2;
    cin >> fools[num1][num2];
    if(num1 == 0 && num2 == 2){
        cout << "Your name monday" << endl;
    }
     else if (num1 == 1 && num2 == 3){
        cout <<"no faith" << endl;
    }else if (num1 == 2 && num2 == 1){
        cout <<"your name cow" << endl;
    }else{
    cout <<"not valid"<<endl;
     }
    return 0;
}
阿马尔·K。

执行此操作时:

cin >> fools[num1][num2];

从控制台读取的输入直接是傻瓜矩阵中的值。如果您这样做:

cin >> fools[0][0];

您在控制台中输入的任何内容都会修改“ cat”并将新值存储为字符串。假设如果输入0 1,它将把“ cat”更改为“ 0 1”。您需要像这样将行和列索引作为输入:

cin >> num1 >> num2;

在您的代码中num1num2它们是未初始化的,并且包含一些随机垃圾值,就像C ++中所有未初始化的局部变量一样。假设num1num2包含12和34的随机值。fools[12][34]由于矩阵没有第34列或第12行,将导致不确定的行为。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章