字符串而不是Cstring c ++

时间:2014-11-02 21:35:13

标签: c++

#include <fstream>
#include <iostream>
using namespace std;

int main ( )
{
    fstream f;
    char cstring[256];
    f.open ( "test.txt", ios::in );
    short counter = 0;
    while ( !f.eof ( ) )
    {
        f.getline ( cstring, sizeof ( cstring ) );
        counter++;
        cout << cstring << endl;
    }
    cout << "Anzahl der Zeilen:" <<counter << endl;
    f.close ( );
    system ( "PAUSE" );
}

我想用std :: string替换Cstring,但f.getline不将它作为参数。

1 个答案:

答案 0 :(得分:3)

成员函数getline()仅适用于原始字符数组。 Modern C ++提供了可用于std::getline()的免费函数std::string

#include <string>

std::string str;
while (std::getline(f, str)) {

}