-1

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;
Oblivion
  • 7,176
  • 2
  • 14
  • 33
  • Maybe you are using a C++ compiler but this is pure C. – H H Oct 27 '19 at 16:17
  • 1
    Whatever it is, it will have to be just as buggy as the C version, since the C version is broken. Maybe you shouldn't pay much attention to C (not C++) code that's broken by design. – Sam Varshavchik Oct 27 '19 at 16:18
  • Look at Console.ReadLine: https://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline – Gabriel Devillers Oct 27 '19 at 16:34

2 Answers2

1

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.

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • And is there a way to enter -1, to end this iteration ? Looks like an endless loop to me. – Holger Oct 27 '19 at 18:15
  • 1
    @Holger: Ctrl-Z gives -1. And that is the sole reason that Read() returns int and not char. – H H Oct 28 '19 at 12:43
0
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();
H H
  • 263,252
  • 30
  • 330
  • 514