为什么我的 foreach 打印出 2 个字符?
Why is my foreach printing out 2 char?
我正在尝试为教育创建加密 (ceasar),但出于某种原因,我似乎无法理解为什么我的简单代码(到目前为止)如此混乱
static void Main(string[] args)
{
string word;
int key = 0;
Console.WriteLine("Write your messages");
word = Console.ReadLine();
Console.WriteLine("Enter your key cypher");
key =int.Parse(Console.ReadLine());
encrypt(word, key);
}
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.Write(otherword);
Console.Read();
}
}
如果我在 "Write your messages" 之后写 test 然后将它放入我的 string word
并在我的函数 encrypt
中使用它,它应该输出
t
e
s
t
但不管出于什么上帝遗弃的原因,我得到这样的输出
t
es
t
我不明白为什么。
那么您可能想使用 Console.WriteLine(otherword);
。输出中换行符的间距取决于您在 Console.Read();
行之后按下的键。 (例如,如果您按 [Enter]
,那么您将得到一个换行符,但如果您按 A
,则不会。)
您可能还应该使用 Console.ReadKey(true);
而不是 Console.Read();
作为分隔输出的方法,因为这样您按下的键就不会出现。
使用 Console.ReadLine()
而不是 Console.Read()
- 或者(甚至更好)删除完全读取的行并使用 Console.WriteLine(otherword)
。 Read()
会扰乱下一行的格式。
您需要在 encrypt
函数中将 Console.Read()
更改为 Console.ReadLine()
。 Console.Read()
只从输入流中读取下一个字符。并且由于按下回车键会生成两个字符:\r\n
,它会循环两次。
在加密方法中 - 将 Console.Write 更改为 Console.Write 行并将 Console.Read() 移到 foreach 之外。
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.WriteLine(otherword);
}
Console.Read();
}
我正在尝试为教育创建加密 (ceasar),但出于某种原因,我似乎无法理解为什么我的简单代码(到目前为止)如此混乱
static void Main(string[] args)
{
string word;
int key = 0;
Console.WriteLine("Write your messages");
word = Console.ReadLine();
Console.WriteLine("Enter your key cypher");
key =int.Parse(Console.ReadLine());
encrypt(word, key);
}
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.Write(otherword);
Console.Read();
}
}
如果我在 "Write your messages" 之后写 test 然后将它放入我的 string word
并在我的函数 encrypt
中使用它,它应该输出
t
e
s
t
但不管出于什么上帝遗弃的原因,我得到这样的输出
t
es
t
我不明白为什么。
那么您可能想使用 Console.WriteLine(otherword);
。输出中换行符的间距取决于您在 Console.Read();
行之后按下的键。 (例如,如果您按 [Enter]
,那么您将得到一个换行符,但如果您按 A
,则不会。)
您可能还应该使用 Console.ReadKey(true);
而不是 Console.Read();
作为分隔输出的方法,因为这样您按下的键就不会出现。
使用 Console.ReadLine()
而不是 Console.Read()
- 或者(甚至更好)删除完全读取的行并使用 Console.WriteLine(otherword)
。 Read()
会扰乱下一行的格式。
您需要在 encrypt
函数中将 Console.Read()
更改为 Console.ReadLine()
。 Console.Read()
只从输入流中读取下一个字符。并且由于按下回车键会生成两个字符:\r\n
,它会循环两次。
在加密方法中 - 将 Console.Write 更改为 Console.Write 行并将 Console.Read() 移到 foreach 之外。
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.WriteLine(otherword);
}
Console.Read();
}