![](/img/trans.png)
[英]How to read first line of file word by word and other lines as line by line store in variables?
[英]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.