簡體   English   中英

從文件行每行讀取一個字符串,僅讀取第一個單詞

[英]Read in a string from file line per line and just the first word

我從這里得到了此代碼。

#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指定的整行。 當我只想閱讀每行的第一個單詞時,我需要更改什么?

提前致謝。

感謝您的答復,約阿希姆·皮爾博格,我可以自己回答我的問題。 我將兩行添加到print_line的末尾:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM