What is the C# equivalent of the following C++ code?
for (char c = getc(stdin); c != -1; c = getc(stdin))
if (c == '\n' || c == '\r')
continue;
else
str[p++] = c;
str[p] = 0;
What is the C# equivalent of the following C++ code?
for (char c = getc(stdin); c != -1; c = getc(stdin))
if (c == '\n' || c == '\r')
continue;
else
str[p++] = c;
str[p] = 0;
You are trying to iterate through user input character and if it is \n
(\n
stands for new line) and \t
(\t
stands for tab/four blank spaces) then skip it otherwise add it to existing string
In C#, we use Console.Read()
to read next character from console, you can use this to read next character from console input, update your code as per your loop and condition.
@Henk used StringBuilder
to avoid creating new string everytime, as StringBuilder
class is mutable.
You can use @HenkHolterman solution to solve your problem, but this answer will help you to understand his code.
var str = new StringBuilder();
for (int c = Console.Read(); c != -1; c = Console.Read())
{
if (c == '\n' || c == '\r')
continue;
str.Append((char)c);
}
string s = str.ToString();