每行从文件行中读取一个字符串,只读取第一个单词
Read in a string from file line per line and just the first word
我从 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
指定的整行。如果我只想阅读每行的第一个单词,我需要更改什么?
提前致谢。
感谢您的回复,Joachim Pileborg,我可以自己回答我的问题。我将这两行添加到 print_line
:
的末尾
int strpos = line.find(" ");
string input = line.substr(0, strpos);
cout << input << endl;
我从 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
指定的整行。如果我只想阅读每行的第一个单词,我需要更改什么?
提前致谢。
感谢您的回复,Joachim Pileborg,我可以自己回答我的问题。我将这两行添加到 print_line
:
int strpos = line.find(" ");
string input = line.substr(0, strpos);
cout << input << endl;