2017-09-21 4 views
0

私の学校でC++クラスを開始したばかりで、言語を学び始めました。ある学校の問題では、私はgetl​​ineを使ってテキストファイルの行をスキップしようとしています。エラー:basic_istream <char>スカラー以外の型cxx11 :: 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

を得ることをコンパイルしようとするたびに、このへの簡単な解決策はありますか?

+1

のgetlineは、文字列http://en.cppreference.com/を返さないあなたのコードにコメントを追加しましたcpp/string/basic_string/getlineで始めるには、まず 'string z ='を削除してみてください。 – alfC

答えて

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 
    } 
} 
関連する問題