Parsing

Parsing is the process of reading a string and converting it into another data type. It comes up often when a program receives input from the user — in most languages, user input always arrives as text, even if the user typed a number.

Parsing is a specific kind of type conversion. For a broader introduction to converting between types, see Type Conversion.

Parsing a String into an Integer#

The most common case: the user types a number, but the program receives it as text. To use it as a number, you parse it.

string input = Console.ReadLine();
int number = int.Parse(input);

int.Parse() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example "abc" — the program will crash.

input_value = input()
number = int(input_value)

int() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example "abc" — the program will crash.

let inputValue = prompt();
let number = parseInt(inputValue);

parseInt() reads the string and returns the integer it represents. If the string cannot be interpreted as a number — for example "abc" — it returns NaN (Not a Number) instead of crashing.

Parsing can fail if the string doesn’t contain a valid value of the expected type. Always make sure the input is valid before parsing, or handle the failure gracefully.

Common Mistakes#

Forgetting to parse user input User input always arrives as a string. Writing number + 1 when number is still a string will either cause an error or produce unexpected results — in JavaScript, "1" + 1 gives "11", not 2.

Passing a literal instead of the variable Writing int.Parse("1") hard-codes the value and ignores what the user actually typed. Always pass the variable that holds the input.

Expecting parsing to round or truncate int.Parse("9.99") does not return 9 — it crashes, because "9.99" is not a valid integer string. Use a different parse function if you need to handle decimals.

Not handling parse failure If there’s any chance the user might enter something invalid, parse failure needs to be handled. int.Parse() and int() crash on bad input. Use safer alternatives like int.TryParse() in C# when validation matters.

Resources#