2017-09-21 20 views
0

我剛剛在我的學校開始一個C++類,我開始學習語言。對於一個學校問題,我試圖用getline跳過文本文件中的行。錯誤: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/ w/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 
    } 
} 
相關問題