[英]Error: basic_istream<char> to non-scalar type cxx11::string while using getline
I just started a c++ class at my school and I am starting to learn the language. 我刚刚在学校开始了c ++课,并且开始学习这种语言。 For one school problem I am trying to skip lines in a text file using getline.
对于一个学校问题,我试图使用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;
}
}
Every time I try to compile that I get the error 每次我尝试编译时都会出现错误
gift1.cpp:22:21: error: conversion from 'std::basic_istream' to non-scalar type 'std::__cxx11::string {aka std::__cxx11::basic_string}' requested
gift1.cpp:22:21:错误:请求从“ std :: basic_istream”转换为非标量类型“ std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}”
Is there any simple solution to this? 有什么简单的解决方案吗?
You have so many problems in this code - so instead of giving you a comment - I added comments to your code 您在此代码中有很多问题-因此,我没有给您注释,而是向您的代码添加了注释
#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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.