gpt4 book ai didi

c++ - 错误:使用 getline 时 basic_istream 变为非标量类型 cxx11::string

转载 作者:行者123 更新时间:2023-11-28 04:59:52 25 4
gpt4 key购买 nike

我刚刚在我的学校开始了一门 c++ 类(class),我正在开始学习这门语言。对于一个学校问题,我试图使用 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: error: conversion from 'std::basic_istream' to non-scalar type 'std::__cxx11::string {aka std::__cxx11::basic_string}' requested

有什么简单的解决办法吗?

最佳答案

你在这段代码中有很多问题 - 所以我没有给你评论 - 我在你的代码中添加了评论

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

关于c++ - 错误:使用 getline 时 basic_istream<char> 变为非标量类型 cxx11::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46335102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com