简体   繁体   English

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

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

I got this Code from 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; 
}

This reads in a whole line specified by lnNo . 这将读取由lnNo指定的整行。 What do I have to change when I just want to read in the first word per line? 当我只想阅读每行的第一个单词时,我需要更改什么?

Thanks in advance. 提前致谢。

Thanks to your response, Joachim Pileborg, I could answer my question by myself. 感谢您的答复,约阿希姆·皮尔博格,我可以自己回答我的问题。 I added the two lines to the end of print_line : 我将两行添加到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