从 C++ 中的文件行和数字中读取
reading from a file lines and numbers in c++
我是 c++ 的新手,我正在练习如何从文件中读取一行字符串,然后是数字,然后是字符串行二。
示例字符串
line one, number, string line two.
有人可以帮我创建一个while循环,我知道如何打开文件。 只需要帮助读取一行字符串,然后再次读取数字和字符串行。
while (?? file >> strline) {
cout << strline;
cout << number;
cout << strline;
}
关于如何解决这个问题的任何建议?提前谢谢。
可以使用std::getline
逐行读取
string strline;
while(getline(file, strline))
{
cout << strline;
}
如果需要数字的实际值,可以使用std::istringstream
(必须#include <sstream>
),例如
string strline;
if(getline(file,strline))
{
// do something with the first line
}
if(getline(file,strline)) // read the second line
{
istringstream ss(strline);
double x;
ss >> x; // dump the number into x
}
if(getline(file, strline))
{
// finally read the third line
}
或者,当然,可以使用类似for
string strline;
int x;
for(int i=0; i<2; i++)
{
istringstream ss;
if(getline(file, strline))
{
if(i == 1) // second line
{
// do something here with ss, like
ss >> x; // dump the number into x
}
}
}
while(file)
{ 获取行(文件,线); 在文件
内读取 Cout <<Strline <<endl; 打印文件中的所有内容
}
相关文章:
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 如何读取具有数字间隔的文本文件?C++
- 如何将uint8_t的二进制表示形式读取为数字
- C++ - 将 int 读取为字母和数字序列
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 我可以从具有不同数字分隔符的istream中读取双值吗
- 如何从文件中读取用空格分隔的数字
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 将任意大小的大量 Base-10 数字读取到位集中
- 无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字
- 将字符串和数字读取到向量C
- C++ 将文件中的数字读取到数组中,然后将其打印到其他数组中
- 将数字读取到矢量
- (c++)试图将数字读取到数组中,在输出中得到垃圾数字
- 在读取文件时,在增加数组大小的同时,将浮点数字读取到动态分配的中
- 猜数字 - 读取错误时无限循环