我制作了一个简单的程序,它将读取由新行分割的文本文件中的函数,并像编程语言一样执行它。这是代码:
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace My_Project
{
class Program
{
public static Dictionary<string, string> variables = new Dictionary<string, string>();
static void Main(string[] args)
{
//string code = args[0];
string code = File.ReadAllText(@"TEXT FILE LOCATION HERE");
var lines = code.Split('\n');
foreach (string line in lines)
{
char[] lineInCharArray = line.ToCharArray();
if (lineInCharArray[0] == '-')
{
string variablename = (lineInCharArray[1]).ToString();
string value = line.Replace("-" + variablename, "");
Console.WriteLine("VARIABLE DEFINED: " + variablename + " - " + value);
variables.Add(variablename, value);
}
if (lineInCharArray[0] == '*')
{
if (lineInCharArray[1] == '*')
{
try
{
string requestedVariable = line.Replace("**", "");
Console.WriteLine("REQUESTED VARIABLE: " +
requestedVariable);
string printedValue = variables[requestedVariable];
Console.WriteLine(printedValue);
}
catch
{
Console.WriteLine("ERROR: ");
List<string> hhh = variables.Keys.ToList();
foreach (string item in hhh)
{
Console.WriteLine("--: " + item);
}
}
}
else
{
string printedValue = line.Replace("*", "");
Console.WriteLine(printedValue);
}
}
if (lineInCharArray[0] == '+')
{
string variable = variables[lineInCharArray[1].ToString()];
Int32 variableInInt = Convert.ToInt32(variable);
Int32 incrementation = Convert.ToInt32(line.Replace("+" + variable, ""));
for (int i = 0; i < incrementation + 1; i++)
{
variableInInt++;
}
variables[lineInCharArray[1].ToString()] = variableInInt.ToString();
}
}
Console.ReadLine();
}
}
}
-a12 // Set a variable named 'a' and set the value to 12
-j8 // Set a variable named 'j' and set the value to 8
**j // Print the value of the variable of 'j'
**a // Print the value of the variable of 'a'
代码输出以下内容:
VARIABLE DEFINED: a - 12
VARIABLE DEFINED: j - 8
REQUESTED VARIABLE: j
ERROR:
--: a
--: j
REQUESTED VARIABLE: a
12
代码已成功分配a
到12和j
到8
,但无法打印j
(a
很好)。它表示即使程序添加j
,也无法在字典中找到键j
。解决方案应输出以下内容:
VARIABLE DEFINED: a - 12
VARIABLE DEFINED: j - 8
REQUESTED VARIABLE: j
8
REQUESTED VARIABLE: a
12
答案 0 :(得分:2)
在我在评论中提出的问题以及您在评论中发布的答案之后,很明显您所拥有的是\r
末尾的换行符(j
),所以看似"j"
的内容并不完全"j"
;相反,它是"j\r"
。
因此,您需要从控制字符中清除从文件中读取的每一行。实际上,您应该从任何不属于有效标识符的字符中清除它们。