如何在 c++ 中将文件中的段落作为单个字符串读取

How to read a paragraph from file as a single string in c++

本文关键字:段落作 单个 读取 字符串 文件 c++      更新时间:2023-10-16

我正在编写一个应该读取文件的c ++程序。如果该文件包含一组句子,比如一个段落,我将如何使整个段落作为单个字符串阅读?当我尝试对此进行编码时,我的程序只能读取第一个单词,并且在看到空格序列时停止。

例如:

如果我的句子是:you are a great programmer.

它应该显示:you are a great programmer.

但我得到的是:you

如何编码这个...谁能帮我举个例子?

这是我到目前为止尝试过的:

string b;
    ifstream inFile( "file.txt", ios::in );
    if ( !inFile ) { cerr << "File could not be opened" << endl; exit( 1 ); } 
    inFile>>b;
默认情况下,

输入流将空格视为字符串拆分分隔符。尝试使用std::getline(),直到换行符。

要阅读整个段落,您可以假设空行指定段落的结尾。因此,请阅读直到到达空行:

std::string read_paragraph( std::istream& is )
{
    std::stringstream ss;
    std::string line;
    do
    {
        std::getline( is , line );
        ss << line;
    } while( line != "" )
    return ss.str();
}

上面的代码逐行读取流线,将当前行存储在line处,并将其刷新到存储段落的std::stringstream中。我们读取输入,直到当前行为空行。

假设段落是单行(以换行符结尾)。

std::ifstream   file("MyData");

std::string  paragraph;
std::getline(file, paragraph);
// Print the line
std::cout << paragraph;

阅读所有段落:

std::ifstream   file("MyData");

std::string  paragraph;
while(std::getline(file, paragraph))
{    
    // Print the line
    std::cout << paragraph;
}

您可以使用带有分隔符的std::getline作为 EOF 字符:

using std::istream::traits_type;
std::string paragraph;
char eof = traits_type::to_char_type(traits_type::eof());
if (std::getline(file, paragraph, eof))
{
    // ...
}