Console类中的Write和WriteLine函数都是用来在控制台上输出字符串或含有变量的复合文本。其中,WriteLine函数用于在控制台上输出一行文本,并自动换行;而Write函数输出后不会自动换行。
对于Write和WriteLine函数来说,都可以将各种基本类型的值、对象直接输出到控制台中,且WriteLine函数可以不带参数,直接换行。
【例Ex_Write】控制台输出
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
int n;
Console::Write(L"请输入杨辉三角的阶数:");
n = Int32::Parse( Console::ReadLine() );
array<int>^ curLineArr = nullptr;
for (int i=0; i<n; i++ )
{
array<int>^ nextLineArr = gcnew array<int>( i+1 );
if ( i<=1 ){
for ( int j=0; j<i+1; j++ )
nextLineArr[j] = 1;
} else {
if ( curLineArr->Length > 1 ){
nextLineArr[0] = 1;
for ( int k=0; k<curLineArr->Length-1; k++ )
{
nextLineArr[k+1] = curLineArr[k] + curLineArr[k+1];
}
nextLineArr[nextLineArr->Length - 1] = 1;
}
}
// 计算输出该行数据前面的空格
String^ strSpace = " "; // 3个空格
Console::Write( strSpace->PadLeft( ( n - i ) * 3 ) );
// 输出该行数据
for each ( int data in nextLineArr )
Console::Write(L"{0, 6}", data );
Console::WriteLine(); // 直接换行
curLineArr = nextLineArr;
}
return 0;
}
编译运行,输入10并按【Enter】键,结果如下:
请输入杨辉三角的阶数:10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
CStdioFile::WriteString
Writes data from a buffer to the file associated with the CStdioFile object.
virtual void WriteString( LPCTSTR lpsz );
Parameters
-
lpsz
-
Specifies a pointer to a buffer containing a null-terminated text string.
The terminating null character ('\0') is not written to the file. Any newline character in lpsz is written to the file as a carriage return–linefeed pair.
WriteString throws an exception in response to several conditions, including the disk-full condition.
This is a text-oriented write function available to CStdioFile and its descendents, and to CArchive. CFile::Write is also available, but rather than terminating on a null character, it writes the requested number of bytes to the file.
CFile::Write
Writes data from a buffer to the file associated with the CFile object.
virtual void Write( const void* lpBuf, UINT nCount );
Parameters
-
lpBuf
-
A pointer to the user-supplied buffer that contains the data to be written to the file.
-
nCount
-
The number of bytes to be transferred from the buffer. For text-mode files, carriage return–linefeed pairs are counted as single characters.