假设我有一个像这样的文本文件
6 3
john
dan
lammar
我可以阅读这些数字,只有当它们位于不同的文件中时我才能阅读这些数字。但这里的数字和名称都在一个文件中。如何忽略第一行并从第二行开始直接阅读?
int main()
{
vector<string> names;
fstream myFile;
string line;
int x,y;
myFile.open("test.txt");
//Im using this for reading the numbers
while(myFile>>x>>y){}
//Would use this for name reading if it was just names in the file
while(getline(myFile,line))
names.push_back(line);
cout<<names[0];
return 0;
}
答案 0 :(得分:1)
我不确定我是否帮助你,但如果你总是想跳过第一行 - 你可以跳过它吗?
int main()
{
vector<string> names;
fstream myFile;
string line;
int x,y;
myFile.open("test.txt");
//skip the first line
myFile>>x>>y;
//Would use this for name reading if it was just names in the file
while(getline(myFile,line))
names.push_back(line);
cout<<names[0];
return 0;
}
答案 1 :(得分:0)
如果您正在使用fstream,请调用ignore()方法:
istream& ignore ( streamsize n = 1, int delim = EOF );
因此变得非常容易:
ifstream file(filename);
file.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore the first line
// read the second line
string name; getline(flie, name);
答案 2 :(得分:0)
尝试这样的事情:
int main()
{
std::vector<std::string> names;
std::fstream myFile;
myFile.open("test.txt");
if( myFile.is_open() )
{
std::string line;
if (std::getline(myFile, line))
{
std::istringstream strm(line);
int x, y;
strm >> x >> y;
while (std::getline(myFile, line))
names.push_back(line);
}
myFile.close();
if( !names.empty() )
std::cout << names[0];
}
return 0;
}