[英]How do I print “\n” explicitly in a string in c++
嗨,我在c ++中有一個未知字符串,包含“ \\ n”,“ \\ t”等。
string unknown1=read_from_file();
如果unknown1 =“ \\ n \\ t \\ n \\ t \\ n \\ n \\ n \\ n \\ n”現在我要打印
"\n\t\n\t\n\n\n\n\n"
到屏幕上,而不是一堆空白。...我該怎么辦? 請記住,我不知道未知數是什么...
需要強調的是,我知道,如果我們為每個這樣的字符將“ \\ n”更改為“ \\ n”,則可以顯式打印\\ n……但是問題是我不知道unknown1里面的內容是什么。從文件中讀取...。
感謝您的回答,但是我們還有其他擔憂:
\\ l 我認為我們不能窮盡所有可能性吧? 是否有內置的C ++函數僅用於輸出相應的字符?
\\n
, \\t
是轉義序列,但是您可以通過在它們之前添加一個額外的\\
來打印它們, \\\\
用於獲得單個反斜杠。 單個反斜杠表示它是一個轉義序列(如果它是有效的轉義序列),但是兩個反斜杠表示反斜杠字符,因此每當需要輸出反斜杠時,只需添加兩個反斜杠即可。
所以,如果您使用
string unknown1="\\n\\t\\n\\t\\n\\n\\n\\n\\n";
您將獲得所需的輸出。
如果您正在讀取文件,請執行以下操作
string unknown1="\n\t\n\t\n\n\n\n\n";
for ( int i = 0 ; i < unknown1.length() ; i++ )
{
if( unknown1[i] == '\n')
cout<<"\\n";
}
這樣,您將必須檢查可能使用的每個轉義序列 。
像這樣,針對您擔心的不可打印字符運行特定檢查。
char c;
while(c!=EOF){
if(c=='\n')printf("\\n");
if(c=='\t')printf("\\t");
and so on and so forth.
c = the next charater;
}
糟糕,我寫的是C而不是C ++,但是@Arun AS具有正確的語法
請參見以下示例。 您可以將自己的字符添加到switch
以擴展其處理的字符。
#include <iostream>
#include <string>
std::string escapeSpecialChars(const std::string& str)
{
std::string result;
for(auto c : str)
{
switch(c)
{
case '\n':
result += "\\n";
break;
case '\t':
result += "\\t";
break;
default:
result += c;
break;
}
}
return result;
}
int main()
{
std::string str = "\n\n\n\t";
std::cout << escapeSpecialChars(str);
return 0;
}
您可以創建自己的函數以使用std :: map打印字符:
void printChar( const char ch )
{
static const std::map< char, std::string > char_map = {
{ '\n', "\\n" }
// add mappings as needed
};
auto found = char_map.find( ch );
if ( found != char_map.end() )
std::cout << found->second;
else
std::cout << ch;
}
// usage
std::string str = "a\nbc";
for ( auto ch : str ) printChar ( ch );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.