错误:<char>使用 getline 时basic_istream为非标量类型 cxx11::string

Error: basic_istream<char> to non-scalar type cxx11::string while using getline

本文关键字:istream 标量 cxx11 string 类型 char lt gt 使用 错误 getline      更新时间:2023-10-16

我刚刚在我的学校开始了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;
}
}

每次我尝试收到错误

礼品1.cpp:22:21:错误:从'std :: basic_istream'转换为non-Scalar type'std :: __ __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}'请求

有什么简单的解决方案?

您在此代码中有很多问题 - 因此,我没有给您评论 - 我在您的代码中添加了评论

#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
    }
}