简体   繁体   English

C ++如何逐字(字符串)读取文件,但将其显示为与文本文件完全相同

[英]C++ How do you read in a file word by word (strings) but display it exactly like the text file

I'm having trouble figuring out how to get newlines to display when outputting text to cmdPrompt. 我很难弄清楚在将文本输出到cmdPrompt时如何显示换行符。 The .text file is something like this: .text文件是这样的:

"Roses are red
 violets are blue
 sugar is sweet
 and so are you"

And my code for the loop is: 我的循环代码是:

#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;
   }

It reads in the text fine but it just displays it like this: 它读入的文本很好,但只显示如下:

Roses are red violets are blue sugar is sweet and so are you

I don't know how to display it exactly like it is in the text file (with the newlines after each statement. I know you can just do while(nextCharacter != newLn) for reading in by chars but strings got me stumped. 我不知道如何完全像在文本文件中显示它一样(每个语句后都有换行符。我知道您可以只用while(nextCharacter!= newLn)来读取字符,但是字符串让我感到困惑。

When you use formatted extraction functions, such as: 使用格式化的提取功能时,例如:

while(ins >> aString){

you lose all the whitespace characters that are present in the stream. 您将丢失流中存在的所有空白字符。

In order to preserve the whitespaces, you can use std::getline . 为了保留空格,可以使用std::getline

std::string line;
while ( getline(ins, line) )
{
   std::cout << line << std::endl; 
}

If you need to extract the individual tokens from the lines, you can process the lines of text using std::istringstream . 如果需要从行中提取单个标记,则可以使用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
   }
}

You are using the "fstream extraction operator" to read in the file content. 您正在使用“ fstream提取运算符”来读取文件内容。 So keep in mind the operator doesn't read take in account white spaces and new lines but it consider them to be the end of the word. 因此请记住,操作员不会读取空格和换行符,但会认为它们是单词的结尾。 So instead use std::getline . 因此,请使用std::getline

while(std::getline(ins, aString) )
    std::cout << aString << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM