简体   繁体   English

如何使用solidity在remix IDE中的数组中插入用户输入数据?

[英]How to insert user input data in an array in remix IDE using solidity?

I am a beginner learning solidity language.我是学习solidity语言的初学者。 How can I insert the user input data in an array in solidity language.如何将用户输入数据插入到 Solidity 语言的数组中。 Following is the code I have coded so far with some errors.以下是我迄今为止编写的代码,但存在一些错误。

pragma solidity ^0.4.19;

contract SampleContract{
    struct User{
      string name;
      uint age;
    }

   User[] users;
   uint i=0;

   constructor(uint _arrayLength)public{
      users.length = _arrayLength;
   }

   function addUsers(string _name, uint _age) public {
    uint i = 0;
    for(i = 0; i < users.length; i++) {
        users.push(_name);
        users.push(_age);
    }
   }

   function getUser() public view returns (User[]) {
       return users;
   }
}

I get the following errors;我收到以下错误;

TypeError: Invalid type for argument in function call.类型错误:函数调用中的参数类型无效。 Invalid implicit conversion from string memory to struct MyContract.User storage ref requested.从字符串内存到结构 MyContract.User 存储引用的无效隐式转换。 users.push(_name); users.push(_name); ^---^ ^---^

TypeError: Invalid type for argument in function call.类型错误:函数调用中的参数类型无效。 Invalid implicit conversion from uint256 to struct MyContract.User storage ref requested.从 uint256 到 struct MyContract.User 存储引用的无效隐式转换请求。 users.push(_age);用户推送(_年龄); ^--^ ^--^

Thank you in advance.先感谢您。

You need to push the whole Struct.你需要推动整个结构。 In your code you are pushing one by one separately..在您的代码中,您分别一一推送..

Correct code is..正确的代码是..

pragma solidity ^0.4.19;

contract SampleContract{
    
    
    struct User{
      string name;
      uint age;
    }

   User[] public users;
   
   //uint i=0;

   constructor(uint _arrayLength) public{
      users.length = _arrayLength;
   }

   function addUsers(string _name, uint _age) public {
    
        users.push(User(_name,_age))-1;
   }

   function getUser(uint i) public view returns (string, uint) {
       return (users[i].name, users[i].age);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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