Home > database >  "Input string was not in a correct format" when trying to print a List
"Input string was not in a correct format" when trying to print a List

Time:09-11

So I've been trying to do a program, which looked really simple at first, but I guess I must have underestimated it. The program is to receive 2 List with Console.ReadLine() and then merge them in a 3rd list, then List.Sort and print it.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Array.Merge
{
    class Program
    {
        static void Main(string[] args)
        {
            string input1 = Console.ReadLine();
            string input2 = Console.ReadLine();
            List<int> numbers1 = input1.Split(" ").Select(int.Parse).ToList();
            List<int> numbers2 = input2.Split(" ").Select(int.Parse).ToList();
            List<int> numbers = new List<int>();
            for (int a = 0; a < numbers1.Count; a  )
            {
                numbers.Add(numbers1[a]);
            }
            for (int b = 0; b < numbers2.Count; b  )
            {
                numbers.Add(numbers2[b]);
            }
            numbers.Sort();
            foreach(int number in numbers)
            {
                Console.Write(number   " ");
            }
            
        }
    }
}

when I submit my 2 lines of input, I get the error "Input string was not in a correct format" in the console. This is the input I am using:

1 2 3 7 9 
2 4 5 7 8

This is what I should be receiving:

1 2 2 3 4 5 7 7 8 9 

CodePudding user response:

  • You should always use TryParse methods if you handle user input
  • Split can contain empty results, if you have multiple consecutive spaces and don't use StringSplitOptions.RemoveEmptyEntries

So this should work and is double safe:

List<int> numbers1 = input1.Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Select(s => (IsValid: int.TryParse(s, out int Value), Value))
        .Where(x => x.IsValid)
        .Select(x => x.Value)
        .ToList();
List<int> numbers2 = input2.Split(' ', StringSplitOptions.RemoveEmptyEntries)
       .Select(s => (IsValid: int.TryParse(s, out int Value), Value))
       .Where(x => x.IsValid)
       .Select(x => x.Value)
       .ToList();

List<int> numbers = numbers1.Concat(numbers2).OrderBy(i => i).ToList();

You can also create a (local) method to not repeat yourself:

List<int> GetValidInts(string s) => s?.Split(' ', StringSplitOptions.RemoveEmptyEntries)
    .Select(s => (IsValid: int.TryParse(s, out int Value), Value))
    .Where(x => x.IsValid)
    .Select(x => x.Value)
    .ToList() ?? new List<int>();

List<int> numbers1 = GetValidInts(input1);
List<int> numbers2 = GetValidInts(input1);
  •  Tags:  
  • c#
  • Related