Hey everyone! I'm just starting with V programming and I'm trying to write a simple program where I read a number input from the user, convert that input to an integer, and then use it in a for loop. Here's my code:
```v
import readline { read_line }
fn main() {
mut height := read_line('Number: ')! // user input goes here
height = height.int()
for i := 1; i <= height; i++ {
for j := 1; j <= i; j++ {
print('*')
}
println('')
}
}
```
When I try to run it, I get the following error:
Can't run code. The server returned an error:
code.v:5:17: error: cannot assign to `height`: expected `string`, not `int`
I'm confused because `.int()` is supposed to convert the string to an integer, but it seems that the variable is still being treated as a string. One user suggested adding `.int()` right after the input, but that just caused a panic. Can anyone explain what's going wrong and how I can fix this? Thanks a lot!
1 Answer
It sounds like V might automatically determine the type of `height` when you declare it. So, when you assign it with `read_line`, it's set as a string, and trying to assign it as an integer later creates a conflict.
To fix this, you could use two separate variables: first read the input into a string variable and then convert that to an integer. Something like this:
```v
mut heightStr := read_line('Number: ')!
mut heightInt := heightStr.int()
```
That way, you maintain clarity and avoid type conflicts. Give it a shot!
Totally agree with that approach! Keeping the input and the integer separate helps avoid confusion. Good luck with your coding!