2010-10-07 20 views
25

sé cómo hacer una consola lee dos números enteros, pero cada entero por él mismo como estolectura de dos números enteros en una línea usando C#

int a = int.Parse(Console.ReadLine()); 
int b = int.Parse(Console.ReadLine()); 

Si entraba en dos números, es decir, (1 2), el valor (1 2), no se puede analizar los enteros lo que quiero es que si ingresé 1 2, entonces lo tomará como dos enteros

Respuesta

22

Una opción sería aceptar una sola línea de entrada como una cadena y luego procesarla. Por ejemplo:

//Read line, and split it by whitespace into an array of strings 
string[] tokens = Console.ReadLine().Split(); 

//Parse element 0 
int a = int.Parse(tokens[0]); 

//Parse element 1 
int b = int.Parse(tokens[1]); 

Un problema con este enfoque es que se producirá un error (por tirar un IndexOutOfRangeException/FormatException) si el usuario no introduce el texto en el formato esperado. Si esto es posible, deberá validar la entrada.

Por ejemplo, con las expresiones regulares:

string line = Console.ReadLine(); 

// If the line consists of a sequence of digits, followed by whitespaces, 
// followed by another sequence of digits (doesn't handle overflows) 
if(new Regex(@"^\d+\s+\d+$").IsMatch(line)) 
{ 
    ... // Valid: process input 
} 
else 
{ 
    ... // Invalid input 
} 

Alternativamente:

  1. Verificar que la entrada se divide en exactamente 2 cadenas.
  2. Utilice int.TryParse para intente para analizar las cadenas en números.
5

Luego primero debe almacenarlo en una cadena y luego dividirlo usando el espacio como símbolo .

3

Lea la línea en una secuencia, divida la cadena y luego analice los elementos. Una versión simple (que debe tener chequeos de errores añadido a él) sería:

string s = Console.ReadLine(); 
string[] values = s.Split(' '); 
int a = int.Parse(values[0]); 
int b = int.Parse(values[1]); 
6

Usted necesita algo así como (sin código de comprobación de errores)

var ints = Console 
      .ReadLine() 
      .Split() 
      .Select(int.Parse); 

Esto lee una línea, se divide en los espacios en blanco y analiza las cadenas divididas como enteros. Por supuesto, en realidad querrá comprobar si las cadenas ingresadas son en realidad números enteros válidos (int.TryParse).

1

en la línea 1, gracias a LinQ y expresión regular (sin verificación de tipos neeeded)

var numbers = from Match number in new Regex(@"\d+").Matches(Console.ReadLine()) 
        select int.Parse(number.Value); 
1
string x; 
int m; 
int n; 

Console.WriteLine("Enter two no's seperated by space: "); 

x = Console.ReadLine(); 
m = Convert.ToInt32(x.Split(' ')[0]); 
n = Convert.ToInt32(x.Split(' ')[1]); 

Console.WriteLine("" + m + " " + n); 

Esto debería funcionar según su necesidad!

1
public static class ConsoleInput 
{ 
    public static IEnumerable<int> ReadInts() 
    { 
     return SplitInput(Console.ReadLine()).Select(int.Parse); 
    } 

    private static IEnumerable<string> SplitInput(string input) 
    { 
     return Regex.Split(input, @"\s+") 
        .Where(x => !string.IsNullOrWhiteSpace(x)); 
    } 
} 
1
int a, b; 
string line = Console.ReadLine(); 
string[] numbers= line.Split(' '); 
a = int.Parse(numbers[0]); 
b = int.Parse(numbers[1]); 
2
string[] values = Console.ReadLine().Split(' '); 
int x = int.Parse(values[0]); 
int y = int.Parse(values[1]); 
0

Prueba esto:

string numbers= Console.ReadLine(); 

string[] myNumbers = numbers.Split(' '); 

int[] myInts = new int[myNumbers.Length]; 

for (int i = 0; i<myInts.Length; i++) 
{ 
    string myString=myNumbers[i].Trim(); 
    myInts[i] = int.Parse(myString); 
} 

espero que ayude :)

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace SortInSubSet 
{ 
    class Program 
    { 

     static int N, K; 
     static Dictionary<int, int> dicElements = new Dictionary<int, int>(); 
     static void Main(string[] args) 
     { 

      while (!ReadNK()) 
      { 
       Console.WriteLine("***************** PLEASE RETRY*********************"); 
      } 

      var sortedDict = from entry in dicElements orderby entry.Key/3 , entry.Value ascending select entry.Value; 

      foreach (int ele in sortedDict) 
      { 
       Console.Write(ele.ToString() + " "); 
      } 

      Console.ReadKey(); 
     } 

     static bool ReadNK() 
     { 
      dicElements = new Dictionary<int, int>(); 
      Console.WriteLine("Please entere the No. of element 'N' (Between 2 and 9999) and Subset Size 'K' Separated by space."); 

      string[] NK = Console.ReadLine().Split(); 

      if (NK.Length != 2) 
      { 
       Console.WriteLine("Please enter N and K values correctly."); 
       return false; 
      } 

      if (int.TryParse(NK[0], out N)) 
      { 
       if (N < 2 || N > 9999) 
       { 
        Console.WriteLine("Value of 'N' Should be Between 2 and 9999."); 
        return false; 
       } 
      } 
      else 
      { 
       Console.WriteLine("Invalid number: Value of 'N' Should be greater than 1 and lessthan 10000."); 
       return false; 
      } 

      if (int.TryParse(NK[1], out K)) 
      { 
       Console.WriteLine("Enter all elements Separated by space."); 
       string[] kElements = Console.ReadLine().Split(); 

       for (int i = 0; i < kElements.Length; i++) 
       { 
        int ele; 

        if (int.TryParse(kElements[i], out ele)) 
        { 
         if (ele < -99999 || ele > 99999) 
         { 
          Console.WriteLine("Invalid Range(" + kElements[i] + "): Element value should be Between -99999 and 99999."); 
          return false; 
         } 

         dicElements.Add(i, ele); 
        } 
        else 
        { 
         Console.WriteLine("Invalid number(" + kElements[i] + "): Element value should be Between -99999 and 99999."); 
         return false; 
        } 

       } 

      } 
      else 
      { 
       Console.WriteLine(" Invalid number ,Value of 'K'."); 
       return false; 
      } 


      return true; 
     } 
    } 
} 
Cuestiones relacionadas