C# 文件流 - 构建一个测验
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/573144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# file stream - build a quiz
提问by Sarit
Were trying to use external file (txt or CSV) in order to create a file stream in C#. The data in the file is that of a quiz game made of :
试图使用外部文件(txt 或 CSV)以在 C# 中创建文件流。文件中的数据是由以下组成的问答游戏的数据:
1 short question 4 possibles answers 1 correct answer
1 个简短问题 4 个可能的答案 1 个正确答案
The program should be able to tell the user whether he answered correctly or not.
程序应该能够告诉用户他的回答是否正确。
I'm looking for an example code/algorithm/tutorial on how to use the data in the external file to create a simple quiz in C#. Also, any suggestions on how to construct the txt file (how do I remark an answer as the correct one?). Any suggestions or links? Thanks,
我正在寻找有关如何使用外部文件中的数据在 C# 中创建简单测验的示例代码/算法/教程。此外,关于如何构建 txt 文件的任何建议(我如何将答案标记为正确的答案?)。任何建议或链接?谢谢,
采纳答案by Noldorin
There's really no set way to do this, though I would agree that for a simple database of quiz questions, text files would probably be your best option (as opposed to XML or a proper database, though the former wouldn't be completely overkill).
确实没有固定的方法可以做到这一点,尽管我同意对于简单的测验问题数据库,文本文件可能是您的最佳选择(与 XML 或适当的数据库相反,尽管前者不会完全矫枉过正) .
Here's a little example of a text-based format for a set of quiz questions, and a method to read the questions into code. Edit:I've tried to make it as easy as possible to follow now (using simple constructions), with plenty of comments!
这是一组测验问题的基于文本格式的小示例,以及将问题读入代码的方法。编辑:我现在试图让它尽可能容易理解(使用简单的结构),并附有大量评论!
File Format
文件格式
Example file contents.
示例文件内容。
Question text for 1st question... Answer 1 Answer 2 !Answer 3 (correct answer) Answer 4 Question text for 2nd question... !Answer 1 (correct answer) Answer 2 Answer 3 Answer 4
Code
代码
This is just a simple structure for storing each question in code:
这只是用于在代码中存储每个问题的简单结构:
struct Question
{
public string QuestionText; // Actual question text.
public string[] Choices; // Array of answers from which user can choose.
public int Answer; // Index of correct answer within Choices.
}
You can then read the questions from the file using the following code. There's nothing special going on here other than the object initializer (basically this just allows you to set variables/properties of an object at the same time as you create it).
然后,您可以使用以下代码从文件中读取问题。除了对象初始值设定项(基本上这只是允许您在创建对象的同时设置对象的变量/属性)之外,这里没有什么特别之处。
// Create new list to store all questions.
var questions = new List<Question>();
// Open file containing quiz questions using StreamReader, which allows you to read text from files easily.
using (var quizFileReader = new System.IO.StreamReader("questions.txt"))
{
string line;
Question question;
// Loop through the lines of the file until there are no more (the ReadLine function return null at this point).
// Note that the ReadLine called here only reads question texts (first line of a question), while other calls to ReadLine read the choices.
while ((line = quizFileReader.ReadLine()) != null)
{
// Skip this loop if the line is empty.
if (line.Length == 0)
continue;
// Create a new question object.
// The "object initializer" construct is used here by including { } after the constructor to set variables.
question = new Question()
{
// Set the question text to the line just read.
QuestionText = line,
// Set the choices to an array containing the next 4 lines read from the file.
Choices = new string[]
{
quizFileReader.ReadLine(),
quizFileReader.ReadLine(),
quizFileReader.ReadLine(),
quizFileReader.ReadLine()
}
};
// Initially set the correct answer to -1, which means that no choice marked as correct has yet been found.
question.Answer = -1;
// Check each choice to see if it begins with the '!' char (marked as correct).
for(int i = 0; i < 4; i++)
{
if (question.Choices[i].StartsWith("!"))
{
// Current choice is marked as correct. Therefore remove the '!' from the start of the text and store the index of this choice as the correct answer.
question.Choices[i] = question.Choices[i].Substring(1);
question.Answer = i;
break; // Stop looking through the choices.
}
}
// Check if none of the choices was marked as correct. If this is the case, we throw an exception and then stop processing.
// Note: this is only basic error handling (not very robust) which you may want to later improve.
if (question.Answer == -1)
{
throw new InvalidOperationException(
"No correct answer was specified for the following question.\r\n\r\n" + question.QuestionText);
}
// Finally, add the question to the complete list of questions.
questions.Add(question);
}
}
Of course, this code is rather quick and basic (certainly needs some better error handling), but it should at least illustrate a simple method you might want to use. I do think text files would be a nice way to implement a simple system such as this because of their human readability (XML would be a bit too verbose in this situation, IMO), and additionally they're about as easy to parse as XML files. Hope this gets you started anyway...
当然,这段代码相当快速和基本(当然需要一些更好的错误处理),但它至少应该说明您可能想要使用的简单方法。我确实认为文本文件是实现这样一个简单系统的好方法,因为它们具有人类可读性(在这种情况下,XML 有点过于冗长,IMO),而且它们与 XML 一样容易解析文件。希望这能让你开始……
回答by Rob
A good place to start is with Microsoft's documentation on FileStream.
一个很好的起点是Microsoft 关于 FileStream 的文档。
A quick google search will give you pretty much everything you need. Here's a tutorialon reading and writing files in C#. Google is your friend.
快速的谷歌搜索将为您提供几乎所有您需要的东西。这是有关在 C# 中读取和写入文件的教程。谷歌是你的朋友。
回答by Cerebrus
My recommendation would be to use an XML file if you must load your data from a file (as opposed to from a database).
如果您必须从文件(而不是从数据库)加载数据,我的建议是使用 XML 文件。
Using a text file would require you to pretty clearly define structure for individual elements of the question. Using a CSV could work, but you'd have to define a way to escape commas within the question or answer itself. It might complicate matters.
使用文本文件需要您为问题的各个元素非常清楚地定义结构。使用 CSV 可以工作,但您必须定义一种方法来转义问题或答案本身中的逗号。这可能会使事情复杂化。
So, to reiterate, IMHO, an XML is the best way to store such data. Here is a short sample demonstrating the possible structure you might use:
因此,重申一下,恕我直言,XML 是存储此类数据的最佳方式。这是一个简短的示例,演示您可能使用的可能结构:
<?xml version="1.0" encoding="utf-8" ?>
<Test>
<Problem id="1">
<Question>Which language am I learning right now?</Question>
<OptionA>VB 7.0</OptionA>
<OptionB>J2EE</OptionB>
<OptionC>French</OptionC>
<OptionD>C#</OptionD>
<Answer>OptionA</Answer>
</Problem>
<Problem id="2">
<Question>What does XML stand for?</Question>
<OptionA>eXtremely Muddy Language</OptionA>
<OptionB>Xylophone, thy Music Lovely</OptionB>
<OptionC>eXtensible Markup Language</OptionC>
<OptionD>eXtra Murky Lungs</OptionD>
<Answer>OptionC</Answer>
</Problem>
</Test>
As far as loading an XML into memory is concerned, .NET provides many intrinsic ways to handle XML files and strings, many of which completely obfuscate having to interact with FileStreams directly. For instance, the XmlDocument.Load(myFileName.xml)
method will do it for you internally in one line of code. Personally, though I prefer to use XmlReader
and XPathNavigator
.
就将 XML 加载到内存而言,.NET 提供了许多处理 XML 文件和字符串的内在方法,其中许多完全混淆了必须直接与 FileStreams 交互的问题。例如,该XmlDocument.Load(myFileName.xml)
方法将在一行代码中为您完成内部操作。就个人而言,虽然我更喜欢使用XmlReader
和XPathNavigator
。
Take a look at the members of the System.Xml namespacefor more information.
查看System.Xml 命名空间的成员以获取更多信息。
回答by user62572
any suggestions on how to construct the txt file (how do I remark an answer as the correct one?)
关于如何构建 txt 文件的任何建议(我如何将答案标记为正确的答案?)
Perhaps the easiest is with a simple text file format - where you have questions and answers on each line (no blank lines). The # sign signifies the correct answer.
也许最简单的方法是使用简单的文本文件格式——每行都有问题和答案(没有空行)。# 符号表示正确答案。
Format of the file -
文件格式——
Question #answer answer answer answer
An example file -
一个示例文件 -
What is 1 + 1? #2 9 3 7 Who is buried in Grant's tomb? Ed John #Grant Tim
I'm looking for an example code/algorithm/tutorial on how to use the data in the external file to create a simple quiz in C#.
我正在寻找有关如何使用外部文件中的数据在 C# 中创建简单测验的示例代码/算法/教程。
Here's some code that uses the example file to create a quiz.
下面是一些使用示例文件创建测验的代码。
static void Main(string[] args)
{
int correct = 0;
using (StreamReader sr = new StreamReader("C:\quiz.txt"))
{
while (!sr.EndOfStream)
{
Console.Clear();
for (int i = 0; i < 5; i++)
{
String line = sr.ReadLine();
if (i > 0)
{
if (line.Substring(0, 1) == "#") correct = i;
Console.WriteLine("{0}: {1}", i, line);
}
else
{
Console.WriteLine(line);
}
}
for (; ; )
{
Console.Write("Select Answer: ");
ConsoleKeyInfo cki = Console.ReadKey();
if (cki.KeyChar.ToString() == correct.ToString())
{
Console.WriteLine(" - Correct!");
Console.WriteLine("Press any key for next question...");
Console.ReadKey();
break;
}
else
{
Console.WriteLine(" - Try again!");
}
}
}
}
}