Skip to content
This repository was archived by the owner on Nov 11, 2019. It is now read-only.

Guessing Game: Number input fails to produce Option int, instead produces Option none #48

Closed
listless opened this issue Jan 23, 2014 · 8 comments

Comments

@listless
Copy link

Running the Guessing Game program at the end of Chapter 11, it does not seem to recognise when I enter a number, instead always producing options of type none, I fixed this by changing
let num = from_str::<int>(input.slice_to(input.len() - 1));
to
let num = from_str::<int>(input.slice_to(input.len() - 2));
because I suspected that this method was trying to remove the \n from the end of the input string, and \n would be two characters.

Sorry, new to github so I believed this would be the best place to post about this, can this problem be confirmed?

@steveklabnik
Copy link
Owner

This is the perfect place, thank you.

Hmmm, strange. I tried the code and it worked for me. What platform are you on?

@listless
Copy link
Author

I'm on 64-bit Windows 7, strange.

@steveklabnik
Copy link
Owner

Hm, I wonder if that's it.

@listless
Copy link
Author

When I run this:

 use std::io::buffered::BufferedReader;
 use std::io;
 
 fn main() {
     println("Input: ");
     let mut reader = BufferedReader::new(io::stdin());
     let input = reader.read_line().unwrap_or(~"nothing");
     println!("{:?}", input.len());
 }

And only press enter, I get an output of 2u, could the output be different on different systems?

@Kimundi
Copy link

Kimundi commented Jan 23, 2014

Could it be that on windows it reads \r\n, while on different systems its only \n?

@listless
Copy link
Author

hmm, maybe.
Testing on a linux machine and I get an output of 1u from the program I posted

Edit: After looking around, I agree with Kimundi that window's use of \r\n as oppose to \n may most likely be the cause of the problem, maybe this could be resolved by BufferReader's read_line() discarding the ending \r and \n when returning the string?

http://static.rust-lang.org/doc/master/std/io/struct.BufferedReader.html

@listless
Copy link
Author

After looking at http://adridu59.github.io/rust-tuts/tutorial/tutorial.html ,
I think another way of converting from str to int could be to use:

let num = from_str::<int>(input.trim_right_chars(& &['\n', '\r']));

This should work for both Windows, OS X and Linux systems, as it'll get rid of the \n, and optionally the \r if it exists.

http://static.rust-lang.org/doc/master/std/str/trait.StrSlice.html#tymethod.trim_right_chars

@steveklabnik
Copy link
Owner

This is going to be changed for 0.11. Please let me know if it still acts up with the new code.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants