在C ++中使用结构

时间:2013-03-21 21:57:03

标签: c++

我在使用结构编程时遇到了麻烦。我想接受(整数,字符)形式的输入,可以重复几次。然后程序将数组中的字符存储在整数所指示的位置。目前,问题是Message未定义且该位置未定义。

struct MessagePiece
{
    int location;
    char message;
};

void readMessage( istream& in, Message message[] )
{
    MessagePiece;
    message[256];
    Message message;

      while ( !in.fail() )
     {
             in >> location; //I'm not sure why this counts as undefined as it is defined in the struct

             if (location < 256, location >= 0)
                in >> message[location];
      }
return;
};

2 个答案:

答案 0 :(得分:2)

未定义,因为location仅存在于MessagePiece

类型的对象的上下文中
MessagePiece mp;
in >> mp.location;

答案 1 :(得分:0)

你应该使用&amp;&amp;而不是','在你的if语句中检查条件。 另外,这些行:

MessagePiece;
message[256];
Message message;

应该写成这样:

MessagePiece messages[256]; //declaring an array of struct MessagePiece
char message; // a char for storing input read from the user. 

还有一件事,要么将消息作为参数,要么在函数本身中声明它。

请考虑阅读一本关于用C ++编程的好书。

相关问题