简体   繁体   中英

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

I am a beginner learning solidity language. How can I insert the user input data in an array in solidity language. 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. users.push(_name); ^---^

TypeError: Invalid type for argument in function call. Invalid implicit conversion from uint256 to struct MyContract.User storage ref requested. 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);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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