I'm trying to read char in cycle, but I don't know why it works wrong. Here is my code:
int sizeOfOurArray;
string resultString;
char buffer;
resultString = "";
Console.WriteLine("Введите количество элементов массива: ");
sizeOfOurArray = int.Parse(Console.ReadLine());
char[] ourArray = new char[sizeOfOurArray];
for (int i = 0; i < ourArray.Length; i++)
{
Console.WriteLine("Введите значение элементу под номером {0}: ", i);
buffer = (char)Console.Read();
resultString += buffer.ToString() + " ";
}
Console.WriteLine(resultString);
Console.ReadKey();
Result is: http://xmag开发者_开发百科es.net/storage/10/1/0/a/6/upload/27c2a69a.png
PS Thanks for answers, it was really helpful!
The problem is that Console.Read
will only return anything when the user hits return - at which point it will return (in multiple calls) each of the characters including the carriage return and line feed.
You could potentially read a line at a time and then take the first character:
string line = Console.ReadLine();
// TODO: Handle the user just hitting return...
char buffer = line[0];
(Note that I'd personally use a StringBuilder
rather than repeated concatenation, but that's a different matter.)
Use Console.ReadKey() to read a single char, like this:
int sizeOfOurArray;
string resultString;
char buffer;
resultString = "";
Console.WriteLine("Введите количество элементов массива: ");
sizeOfOurArray = int.Parse(Console.ReadLine());
char[] ourArray = new char[sizeOfOurArray];
for (int i = 0; i < ourArray.Length; i++)
{
Console.WriteLine("Введите значение элементу под номером {0}: ", i);
buffer = Console.ReadKey().KeyChar;
resultString += buffer.ToString() + " ";
}
Console.WriteLine();
Console.WriteLine(resultString);
Console.ReadKey();
Hope this helps
string input = Console.ReadLine();
resultString += (String.IsNullOrEmpty(input)) ? "" : input[0].ToString();
solves it.
A slight change to your code, this works for me:
using System;
using System.Text;
public static class SOQ {
public static void Main( string[] argv ){
Console.Error.Write("Enter the number of characters: ");
// far from ideal but illustrates your code
var count = int.Parse(Console.ReadLine());
var buffer = new StringBuilder();
for ( int i = 0; i < count; i++ ){
Console.Error.Write("\n{0}:",i+1);
var c = (char)Console.Read();
buffer.Append(c.ToString());
}
Console.WriteLine();
Console.WriteLine("Result: `{0}'", buffer.ToString());
}
}
精彩评论