我是C#和VS的新手,我只是尝试使用Console.WriteLine(...)打印一行,但它只显示在命令提示符中。有没有办法在输出窗口中显示输出?
编辑:这是一个控制台应用程序。
另外,如何访问命令行以运行程序?我只能弄清楚如何使用F5运行,但如果我需要输入参数,这将无效。
答案 0 :(得分:10)
如果是ConsoleApplication,那么Console.WriteLine
将编写控制台。如果您使用Debug.Print
,它将打印到底部的输出标签。
如果要添加命令行参数,可以在项目属性中找到它。点击Project -> [YourProjectName] Properties... -> Debug -> Start Options -> Command line arguments
。此处的文本将在运行时传递给您的应用程序。您也可以在构建之后运行它,方法是在构建它之后通过bin\Release
或bin\Debug
文件夹运行它,或者根据您的喜好运行它。我发现以这种方式测试各种参数比较容易,而不是每次都设置命令行参数。
答案 1 :(得分:2)
Yes I ran into this problem too, my first 2 days with VS2012. Where is my console output? it flashes and disappears. Mystified by usefull examples like
https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
Ok, indeed @martynaspikunas .. trick you can replace Console.WriteLine() by Debug.WriteLine() to see it in the IDE. It will stay there, nice.
But sometimes you have to change a lot of places in existing code to do that.
I did find a few alternatives.. How about a single
Console.ReadKey();
in Program.cs ? The console will wait for you, it can scroll..
I also like to use the Console output in my Winforms contexts:
class MyLogger : System.IO.TextWriter
{
private RichTextBox rtb;
public MyLogger(RichTextBox rtb) { this.rtb = rtb; }
public override Encoding Encoding { get { return null; } }
public override void Write(char value)
{
if (value != '\r') rtb.AppendText(new string(value, 1));
}
}
Add this class after your main form class. Then plug it in, using the following redirect statement in the constructor, after InitializeComponent() is called:
Console.SetOut(new MyLogger(richTextBox1));
As a result of this, all your Console.WriteLine() will appear in the richTextBox.
Sometimes I use it to redirect to a List to report Console later, or dump it to a textfile.
Note: the MyLogger code snippet was put here by Hans Passant in 2010,
答案 2 :(得分:0)
这是一个保持控制台及其输出的简单技巧:
int main ()
{
cout << "Hello World" << endl ;
// Add this line of code before your return statement and the console will stay up
getchar() ;
return 0;
}
答案 3 :(得分:0)
using System;
#region Write to Console
/*2 ways to write to console
concatenation
place holder syntax - most preferred
Please note that C# is case sensitive language.
*/
#region
namespace _2__CShrp_Read_and_Write
{
class Program
{
static void Main(string[] args)
{
// Prompt the user for his name
Console.WriteLine("Please enter your name");
// Read the name from console
string UserName = Console.ReadLine();
// Concatenate name with hello word and print
//Console.WriteLine("Hello " + UserName);
//place holder syntax
//what goes in the place holder{0}
//what ever you pass after the comma i.e. UserName
Console.WriteLine("Hello {0}", UserName);
Console.ReadLine();
}
}
}
I hope this helps