Ask coding questions

← Back to all posts
How do I use input user data on here?
DuvallRoberts (0)

I'm trying to make a basic project that uses user input and prints it with R and I think I know the code but it won't work.
Below are some example code in R that tried:
~
age <- readline(prompt="Enter age: ")
age <- as.integer(age)

print(age)

~
cat("1) For Addition\n")
cat("2) For Subtraction\n")
cat("3) For Division\n")
cat("4) For multiplication\n")
n1<-readline(prompt="Enter first number:")
n2<-readline(prompt="Enter second number:")
choice<-readline(prompt="Enter your choice:")
n1<- as.integer(n1)
n2<- as.integer(n2)
choice<- as.integer(choice)
if(choice==1){
sum <-(n1+n2)
cat("sum=",sum)
}else if(choice==2){
sub<-(n1-n2)
cat("sub=",sub)
}else if(choice==3){
div<-n1/n2
cat("Division=",div)
}else if(choice==4){
mul<-n1*n2
cat("mul=",mul)
}else{
cat("wrong choice")
}

Can I get some help?

Comments
hotnewtop
theangryepicbanana (1697)

What error(s) did you get?

DuvallRoberts (0)

@theangryepicbanana  r main.r
Enter age:
[1] NA

r main.r
1) For Addition
2) For Subtraction
3) For Division
4) For multiplication
Enter first number:
Enter second number:
Enter your choice:
Error in if (choice == 1) { : missing value where TRUE/FALSE needed
exit status 1

This copied and pasted. It won't let me add any inputs.

theangryepicbanana (1697)

@DuvallRoberts apparently readline can only be used in interactive mode (and not in a standalone script like running code on replit). You'll probably want to use readLines(n=1) instead