字符串而不是 Cstring c++

String instead of Cstring c++

本文关键字:Cstring c++ 字符串      更新时间:2023-10-16
#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 不将其作为参数。

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

#include <string>
std::string str;
while (std::getline(f, str)) {
}