2010-10-07 4 views
25

je sais comment faire une console lu deux entiers, mais chaque entier par elle-même comme celui-cilecture de deux entiers dans une ligne en utilisant C#

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

si je suis entré deux chiffres, à savoir (1 2), la valeur (1 2), je ne peux pas analyser les nombres entiers ce que je veux, c'est que si je saisis 1 2 alors il le prendra comme deux entiers

Répondre

22

Une option consisterait à accepter une seule ligne d'entrée sous forme de chaîne, puis à la traiter. Par exemple:

//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 problème avec cette approche est qu'il échouera (en jetant un IndexOutOfRangeException/FormatException) si l'utilisateur ne saisit pas le texte dans le format attendu. Si cela est possible, vous devrez valider l'entrée.

Par exemple, avec des expressions régulières:

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 
} 

Autre possibilité:

  1. Vérifiez que l'entrée se divise en exactement 2 cordes.
  2. Utilisez int.TryParse à pour d'analyser les chaînes en nombres.
5

Ensuite, vous devez d'abord le stocker dans une chaîne, puis le diviser en utilisant l'espace comme un jeton .

3

Lire la ligne dans une chaîne, diviser la chaîne, puis analyser les éléments. Une version simple (qui doit avoir la vérification d'erreurs ajouté à ce) serait:

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

Vous avez besoin quelque chose comme (pas de code de contrôle d'erreur)

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

Ce lit une ligne, séparation sur les espaces et analyse les chaînes divisées en entiers. Bien sûr, en réalité, vous voulez vérifier si les chaînes entrées sont en fait des entiers valides (int.TryParse).

1

en 1 ligne, grâce à LINQ et expression régulière (sans vérification de type 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); 

Cela devrait fonctionner selon vos besoins!

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

Essayez ceci:

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); 
} 

Hope it helps :)

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; 
     } 
    } 
} 
Questions connexes