C++ 中的 wcerr 對象是類 ostream 的對象。它與標準 C 錯誤輸出流 stderr 相關聯。
cerr 和 wcerr 的區別
cerr
使用 char(narrow character) 作為字符類型。它可用於 ASCII 和 ANSI 字符。
對於國際化,我們需要不適合 char 的 Unicode 字符串。 wcerr
使用 wchar_t
(寬字符)並可用於 Unicode 字符。
wcout 和 wcerr 的區別
初學者 C++ 程序員使用 cout
和 wcout
來顯示錯誤,使用標準輸出來調試他們的程序,但使用 cerr
和 wcerr
來顯示錯誤始終是一個好習慣。
這是因為您可以稍後更改錯誤流以將錯誤寫入文件,而不是在屏幕上顯示錯誤流。
wcerr 聲明
extern wostream wcerr;
它在<iostream> 頭文件中定義。
wcerr
對象確保在第一次構造ios_base::Init
類型的對象期間或之前被初始化。構造wcerr
對象後,表達式(wcerr.flags & unitbuf)
不為零,這意味著發送到這些流對象的任何輸出都會立即刷新到操作係統。另外 wcerr.tie() == &wcout
即 wcerr.tie()
返回 &wcout
這意味著 wcout.flush()
在 wcerr
上的任何輸出操作之前執行。
wcerr
中的"wc" 指的是"wide character",'err' 表示"error",因此 wcerr 表示“寬字符錯誤”。 wcerr
對象與插入運算符 (
wcerr << varName;
或者
wcerr << "Some String";
提取運算符可以與變量、字符串和操縱器的組合多次使用(如 endl
):
wcerr << var1 << "Some String" << var2 << endl;
示例:wcerr 是如何工作的?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileName[] = "data.txt";
wifstream infile(fileName);
if(infile)
wcout << infile.rdbuf();
else
wcerr << "Error while opening the file " << fileName << endl;
return;
}
運行程序時,輸出將是:[如果文件無法打開]
Error while opening the file data.txt
相關用法
- C++ wcstold()用法及代碼示例
- C++ wctrans()用法及代碼示例
- C++ wcsftime()用法及代碼示例
- C++ wcstod()用法及代碼示例
- C++ wcscspn()用法及代碼示例
- C++ wcsncmp()用法及代碼示例
- C++ wcin用法及代碼示例
- C++ wcstok()用法及代碼示例
- C++ wcsstr()用法及代碼示例
- C++ wcsrchr()用法及代碼示例
- C++ wctob()用法及代碼示例
- C++ wcsncpy()用法及代碼示例
- C++ wcslen()用法及代碼示例
- C++ wcsspn()用法及代碼示例
- C++ wclog用法及代碼示例
- C++ wcschr()用法及代碼示例
- C++ wctomb()用法及代碼示例
- C++ wcstof()用法及代碼示例
- C++ wcstol()用法及代碼示例
- C++ wcspbrk()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ wcerr。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。