C# Console.ReadLine()实例讲解

时间:2022-04-06
本文章向大家介绍C# Console.ReadLine()实例讲解,主要分析其语法、参数、返回值和注意事项,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

此方法用于从标准输入流中读取下一行字符。它在Console类(系统命名空间)下。如果标准输入设备是键盘,则ReadLine方法将阻塞,直到用户按下Enter键。而且,如果将标准输入重定向到文件,则此方法将从文件读取一行文本。

用法: public static string ReadLine ();

返回值:它从输入流中返回字符串类型的下一行字符;如果没有更多行可用,则返回null。


异常:

  • IOException:如果发生I /O错误。
  • OutOfMemoryException:如果没有足够的内存为返回的字符串分配缓冲区。
  • ArgumentOutOfRangeException:如果下一行字符中的字符数大于MaxValue。

以下示例程序旨在说明上述方法的用法:

示例1:在这里,请用户输入。由于age是一个整数,因此我们使用Convert.ToInt32()方法进行了类型转换。它从输入流中读取下一行。直到按Enter键,它才会阻塞。因此,它通常用于暂停控制台,以便用户可以检查输出。

// C# program to illustrate 
// the use of Console.ReadLine() 
using System; 
using System.IO; 
  
class GFG { 
      
    // Main Method 
    public static void Main() 
    { 
        int age; 
        string name; 
  
        Console.WriteLine("Enter your name: "); 
          
        // using the method 
        // typecasting not needed  
        // as ReadLine returns string 
        name = Console.ReadLine(); 
          
        Console.WriteLine("Enter your age: "); 
          
        // Converted string to int 
        age = Convert.ToInt32(Console.ReadLine()); 
          
        if (age >= 18)  
        { 
            Console.WriteLine("Hello " + name + "!"
                        + " You can vote"); 
        } 
        else { 
            Console.WriteLine("Hello " + name + "!"
                + " Sorry you can't vote"); 
        } 
    }  
}

输出:

示例2:暂停控制台

// C# program to illustrate 
// the use of Console.ReadLine() 
// to pause the console 
using System; 
using System.IO; 
  
class Geeks { 
      
    // Main Method 
    public static void Main() 
    { 
        string name; 
        int n; 
  
        Console.WriteLine("Enter your name: "); 
          
        // typecasting not needed as  
        // ReadLine returns string 
        name = Console.ReadLine(); 
          
        Console.WriteLine("Hello " + name +  
             " Welcome to GeeksforGeeks!"); 
          
        // Pauses the console until  
        // the user preses enter key 
        Console.ReadLine();  
    }  
}

输出:

说明:在上面的输出中,您可以看到控制台已暂停。光标将连续闪烁,直到您按Enter键。

参考: