C ++:在文件中向后移动 [英] C++: Moving backwards in a file
本文介绍了C ++:在文件中向后移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想向后移动并提取出现"new"的整个行.
I want to move backwards and extract the whole line in which ''new'' occurs.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
char word[30];
string filename;
cout << "Name your file> ";
getline( cin, filename );
fstream file( filename.c_str() );
if (!file)
{
cout << "I could not open the file. Fooey.\n";
return EXIT_FAILURE;
}
else
{
string line;
while (!file.eof())
{
file >> word;
if(strcmpi(word,"new")==0)
{
/*getline( file, line );
cout << line;*/
}
}
file.close();
}
return EXIT_SUCCESS;
}
推荐答案
为什么不逐行阅读文件(使用 ^ ]),然后在行内搜索"new"
字符串?这样(成功完成找到 [
Why don''t you read the file line by line (using std::getline[^]), and search the"new"
string inside the line? This way (on successful find[^] call) you already have the needed line.
[updated]
Something like this (not tested):
do
{
getline( file, line);
if ( ! file.good() ) break; // end of file or some other error
if ( line.find("new") != string::npos)
{
// found: here 'line' is the wanted line.
}
} while ( true );
[/updated]
[/updated]
@cpallini-谢谢您的帮助..请写一些代码片段来解决我的问题.我对编程非常陌生..我尝试了您的建议,但徒劳地..thanx
@cpallini - thanx a lot for your help.. can you please write in a little code snippet to solve my problem. i am very new to programming.. i tried what you suggested but in vain..thanx again
非常感谢.....这是我的第一个任务..taht是为什么我被愚蠢的事情困住了...我真的很感谢您抽出时间来解决我的问题..再次感谢
Thank you so much it worked....Its my first assignment ..taht is why i am getting stuck at stupid things...i am really thankful to you that you took out time for solving my problem ..thanks once again
这篇关于C ++:在文件中向后移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文