简体   繁体   English

在 C# 中读取具有各种变量类型的行

[英]Reading a line with various variable types in C#

I am trying to read a line that consists of: 1 char and 2 integers.我正在尝试读取包含以下内容的行:1 个字符和 2 个整数。

My code looks like this:我的代码如下所示:

char userHint = Convert.ToChar(Console.Read());
        
string[] v = Console.ReadLine().Split();

int a, b;

a = int.Parse(v[0]);
b = int.Parse(v[1]);

I recieve error System.FormatException: 'Input string was not in a correct format.'我收到错误System.FormatException: 'Input string was not in a correct format.' . .

Sample input char: 'O' Sample input ints: 1 2示例输入字符:'O' 示例输入整数:1 2

As I understand, you want to split your string and then convert the characters to integer.据我了解,您想拆分字符串,然后将字符转换为 integer。

This code does what you try to do.此代码执行您尝试执行的操作。

char userHint = Convert.ToChar(Console.ReadLine());

char[] v = Console.ReadLine().ToCharArray();

 int a, b;

 a = Int32.Parse(v[0].ToString());
 b = Int32.Parse(v[1].ToString());

 Console.WriteLine("a: "+ a);
 Console.WriteLine("b: "+ b);

We use Console.ReadLine() so when we press enter the program can wait for the next input我们使用Console.ReadLine()所以当我们按下回车时程序可以等待下一个输入

Instead of string[] we use char[] because we split the input using ToCharArray() .我们使用char[]而不是string[] ] 因为我们使用ToCharArray()拆分输入。

And then parse.然后解析。

Input:输入:

3
78

Output: Output:

a: 7
b: 8

My problem can be solved by reading a char like so:我的问题可以通过读取这样的字符来解决:

char userHint = Convert.ToChar(Console.ReadLine()[0]);

And then read the two integers:然后读取两个整数:

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

int a, b;

a = int.Parse(v[0]);
b = int.Parse(v[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM