我刚开始在学校开设c ++课程,我开始学习这门语言。对于一个学校问题,我试图使用getline跳过文本文件中的行。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int np;
ifstream fin("gift1.txt.c_str()");
string s;
fin >> np;
string people[np];
for(int counter = 0; counter == 1 + np; ++counter)
{
string z = getline(fin, s)
cout << z << endl;
}
}
每次我尝试编译时都会收到错误
gift1.cpp:22:21:错误:从'std :: basic_istream'转换为非标量类型'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}''
这有什么简单的解决方案吗?
答案 0 :(得分:1)
您在此代码中遇到了很多问题 - 所以我没有给您发表评论,而是在代码中添加了评论
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int np;
ifstream fin("gift1.txt.c_str()");
string s; // declare this inside the loop
fin >> np;
string people[np]; // This is a Variable Length array. It is not supported by C++
// use std::vector instead
for(int counter = 0; counter == 1 + np; ++counter)
// End condition is never true, so you never enter the loop.
// It should be counter < np
{
string z = getline(fin, s) // Missing ; and getline return iostream
// see next line for proper syntax
//if(getline(fin, s))
cout << z << endl; // Result will be in the s var.
// Discard the z var completely
}
}