我的代码的想法是将文件写入文件(.txt)然后读取该文件,如果读取的字母是辅音,则输出它。如果没有,什么都不做。
我正在使用信号量来做到这一点。创建了两个线程。它从文件写入和读取。但是,无法运行此条件。出于某种原因,从文件中读取时会显示转换错误。并且“letter”变量等于'\ 0'。
namespace Sema
{
class Program
{
private static Semaphore sPhore = new Semaphore(2, 2);
public static string path = "message.txt";
private static void write(object input)
{
Console.WriteLine("\nEnter the consonant: ");
sPhore.WaitOne();
input = Console.ReadLine();
TextWriter tw = File.CreateText(path);
tw.WriteLine(input);
tw.Close();
sPhore.Release();
}
private static void read(object input)
{
sPhore.WaitOne();
char letter = Convert.ToChar(File.ReadAllLines(path));
//char letterChar = Convert.ToChar(letter);
if (letter.Equals('q') || letter.Equals('w') || letter.Equals('r') || letter.Equals('t') || letter.Equals('p') || letter.Equals('s')
|| letter.Equals('d') || letter.Equals('f') || letter.Equals('g') || letter.Equals('h') || letter.Equals('j') || letter.Equals('k')
|| letter.Equals('l') || letter.Equals('z') || letter.Equals('x') || letter.Equals('c') || letter.Equals('v') || letter.Equals('b')
|| letter.Equals('n') || letter.Equals('m'))
{
Console.WriteLine("\nYou wrote this consonant:" + letter);
}
//TextReader tr = File.OpenText("message.txt");
//Console.Write("\nYou wrote this char:" + tr.ReadAsync());
//tr.Close();
sPhore.Release();
}
//private static void read(object path)
//{
//}
static void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
Thread ss = new Thread(new ParameterizedThreadStart(write));
Thread sss = new Thread(new ParameterizedThreadStart(read));
ss.Start(i);
ss.Join();
sss.Start(i);
sss.Join();
}
Console.ReadLine();
}
}
}
答案 0 :(得分:1)
读取所有行返回string []。为了将其转换为char,您需要从第一行获取第一行和第一个char:
char letter = File.ReadAllLines(path)[0][0];