How to convert a string to u32?

How do I convert a string to u32?

Currenty use

let num: u32 = input_string.trim().parse()?;	

My current code:

use std::io;

fn main() {
    loop {
	
		let mut celcius = 0.0;
		let mut farenheit = 0.0;
		println!("Write 1 for celcius or 0 for farenheit");
		let mut input_u32:u32 = 0;
		
		input_u32 = readInputLine();
		
		
		if input_u32 == 1
		{
			println!("Converting from celcius to farenheit");
			println!("Enter celcius")
				
				
		} else {
			println!("Converting from farenheit to celcius");
		}
	
	}
}

fn readInputLine () -> u32 {
	let mut input_string = String::new();
	loop {
	
	
	io::stdin()
	.read_line(&mut input_string)
	.expect("Failed to read line");
	
	
	let input_string: u32 = match input_string.trim().parse() {
			Ok(num) => num,
			Err(_) => continue,
		};
	
	}
	
	let num: u32 = input_string.trim().parse()?;		// <-- ERROR HERE!!
	return num;
}

I think I found the solution:

https://stackoverflow.com/questions/27043268/convert-a-string-to-int

The way you have found is correct. The error you encountered is that the question mark operator can only be used in functions that return a Result. To fix this, either:

  • Change the return type of readInputLine to Result<u32, SomeErrorType>, or
  • Replace the question mark with a call to .unwrap() to crash the program on error, or
  • Otherwise handle the error.
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.