从每行的文件行读取一个字符串,只读取第一个单词

时间:2015-11-10 13:48:18

标签: c++ fstream ifstream

我从here获得了此代码。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <limits> // numeric_limits 

void print_line( const std::string& filename, int lnNo ) 
{ 
    using namespace std; 
    ifstream file( filename.c_str() ); 
    if( !file.is_open() ) 
    { 
        cerr << "Fehler beim Oeffnen der Datei " << filename << endl; 
        return 0; 
    } 
    for( ; lnNo > 1; --lnNo ) 
        file.ignore( numeric_limits< streamsize >::max(), '\n' ); 
    string line; 
    if( !getline( file, line ) ) 
    { 
        cerr << "Fehler beim Lesen aus der Datei " << filename << endl; 
        return 0; 
    } 
    cout << line << endl; 
} 

int main () 
{ 
    using namespace std; 
    for( int lnNo; cin >> lnNo; ) 
        print_line( "input.txt", lnNo ); 
    return 0; 
}

这读取lnNo指定的整行。当我只想读出每行的第一个单词时,我需要改变什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

感谢你的回复,Joachim Pileborg,我可以自己回答我的问题。我将这两行添加到print_line的末尾:

int strpos = line.find(" ");
string input = line.substr(0, strpos);
cout << input << endl;
相关问题