[英]C++ How do you read in a file word by word (strings) but display it exactly like the text file
我很難弄清楚在將文本輸出到cmdPrompt時如何顯示換行符。 .text文件是這樣的:
"Roses are red
violets are blue
sugar is sweet
and so are you"
我的循環代碼是:
#define newLn "\n"
ifstream ins; //these two are near the top where the programs opens the file
string aString;
while(ins >> aString){
if(aString != newLn){
cout << aString << ' ';
}
else
cout << endl;
}
它讀入的文本很好,但只顯示如下:
Roses are red violets are blue sugar is sweet and so are you
我不知道如何完全像在文本文件中顯示它一樣(每個語句后都有換行符。我知道您可以只用while(nextCharacter!= newLn)來讀取字符,但是字符串讓我感到困惑。
使用格式化的提取功能時,例如:
while(ins >> aString){
您將丟失流中存在的所有空白字符。
為了保留空格,可以使用std::getline
。
std::string line;
while ( getline(ins, line) )
{
std::cout << line << std::endl;
}
如果需要從行中提取單個標記,則可以使用std::istringstream
處理文本行。
std::string line;
while ( getline(ins, line) )
{
cout << line << std::endl;
std::istringstream str(line);
std::string token;
while ( str >> token )
{
// Use token
}
}
您正在使用“ fstream提取運算符”來讀取文件內容。 因此請記住,操作員不會讀取空格和換行符,但會認為它們是單詞的結尾。 因此,請使用std::getline
。
while(std::getline(ins, aString) )
std::cout << aString << std::endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.