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);
}
}