ikel
ikel

Reputation: 1978

parsing pasted text in console application

I have a console application made of C#

it allows user to paste some text as following

aaaaa
bbbbb
ccccc

i know console.readline() wont take it, so I used console.in.readtoend()

            string input = Console.In.ReadToEnd(); 

            List<string> inputlist = input.Split('\n').ToList(); 

I need it to parse input text line by line the above code works, but after pasting, in order to conintue, user has to hit enter once, then hit ctrl+z then hit enter again.

im wondering if there is better way to do it something that requires just hit enter key once

any suggestions?

thanks

Upvotes: 1

Views: 2034

Answers (4)

Dainius
Dainius

Reputation: 147

In console if you paste a block of lines they are not executed immediately. That is if you paste

aaaa
bbbb
cccc

nothing happens. Once you hit enter, Read method starts doing it's job. And ReadLine() returns after every new line. So the way I always do it, and IMO it's the easiest way:

var lines = new List<string>();
string? line;
while ((line = Console.ReadLine()) != null)
{
    // Either you do here something with each line separately or
    lines.Add(line);
}
// You do something with all of the lines 

Upvotes: 6

Inder Preet
Inder Preet

Reputation: 114

I was able to solve your issue through the below code. You just need to press enter once you have pasted all your text .

    Console.WriteLine("enter line");
    String s;
    StringBuilder sb = new StringBuilder();
    do
    {
        s = Console.ReadLine();
        sb.Append(s).Append("\r\n");
    } while (s != "");
    Console.WriteLine(sb);
  

Upvotes: 0

Luke Schoen
Luke Schoen

Reputation: 765

I understand now why the question was hard. Does this work for you?

Console.WriteLine("Ctrl+c to end input");
StringBuilder s = new StringBuilder();
Console.CancelKeyPress += delegate
{
    // Eat this event so the program doesn't end
};

int c = Console.Read();
while (c != -1)
{
    s.Append((char)c);
    c = Console.Read();
}

string[] results = s.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

You dont need to do anything extra. just read by ReadLine and then hit enter.

string line1 = Console.ReadLine(); //aaaaa
string line2 = Console.ReadLine(); //bbbbb
string line3 = Console.ReadLine(); //ccccc

Upvotes: 0

Related Questions