如何在 c++ 中将文件中的段落作为单个字符串读取
How to read a paragraph from file as a single string in c++
我正在编写一个应该读取文件的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))
{
// ...
}
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 在C++游戏中与库存系统作斗争
- Eclipse CDT:单个项目中有多个C++文件
- 为什么我们将单个或多维数组的大小声明为常量值?
- C++调用具有 *this 属性的单个帮助程序函数
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 如何将可变参数模板转换为多个单个模板?(C++竞争编程调试模板)
- 将多个 for 循环组合成单个迭代器
- 如何将多种语言设置放在单个 .clang 格式文件中
- QT QOpenGLWidget:如何在不使用数据块复制的情况下修改VBO中的单个顶点值?
- 在 c++ 中对单个排序数组中的 2 个未排序数组进行排序
- 与多个 for 循环与单个 for 循环 wrt 相关的性能从多映射获取数据
- C++:如何用单个命令替换复杂的迭代?
- C++单个生成文件多个二进制文件
- 将单个未唱的 int 发送到 VBO
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 如何限制在C++中为单个类创建的对象数量?
- 字符串中单个字符作为数组的数据类型是什么
- 如何在 c++ 中将文件中的段落作为单个字符串读取