我是 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; 打印文件中的所有内容
}