我试图在C++中实现一个函数,该函数在文件中搜索字符串,然后打印包含该字符串和X后续行的行。
我有下面的代码,用于查找字符串和打印行,但我无法让它用字符串打印行下的行。
void repturno(void){
system("cls");
string codemp, line,output;
bool found = false;
ifstream myfile ("Pacientes.csv");
//captures the string that i need to look for, in this case an employee code
cout<<"\nBienvenida enfermera en turno, por favor introduzca su codigo"<<endl;
cin.ignore();
getline(cin,codemp);
system("cls");
/*reads the file and searches for the string, then prints the whole line, then searches again for
the string and if finds it, will print the whole line again*/
while (getline(myfile, line)) {
if (line.find(codemp) != string::npos) {
cout<<line<<endl;
getline(myfile,line);
found = true;
}
}
//using this to check if the code was working, and verifying if the string was found or not :P
if( found == false){
cout <<"No se encontro la cadena"<< endl;
}
system("pause");
return menu();
}
以下是我的问题:
gotoxy
或'\t'
进行适当间距时也是如此。我不得不逐行保存数据,每一个类别都在一个不同的行中,这样我就可以在程序的其他部分正确地显示它。我用伪代码提供了两个解决方案,但我不知道如何将它们转换为C++语句:注意:搜索循环已经在上面的代码中定义了,所以不会在伪代码中一步一步地分解它,将其称为搜索循环。
伪码#1
START SEARCH LOOP
SEARCH for the desired string(`codemp`) line by line
IF string is found
PRINTLINE containing the STRING
MOVE CURSOR one line below
PRINT the entire line
MOVE CURSOR one line below
PRINT the entire line
MOVE CURSOR one line below
PRINT the entire line
MOVE CURSOR one line below
PRINT the entire line
Move CURSOR one line below
RESTART SEARCH LOOP in the current line
IF NO matching string is found AND EOF
END IF
END SEARCH LOOP
END PROGRAM
Psuedo代码2
START SEARCH LOOP
SEARCH for the desired string(codemp) line by line
IF string is found
PRINTLINE containing the string
PRINTING LOOP
MOVE CURSOR one line below
ASSIGN line to a temp_string
IF temp_string = "\n\n"
//each employee is separated by 2 whitelines after its info
DO NOTHING
ELSE
PRINTLINE temp_string
RESTART PRINTING LOOP
END IF
END PRINTING LOOP
RESTART SEARCH LOOP
IF NO string is found AND EOF
END SEARCH LOOP
END PROGRAM
我希望这是清楚和详细的。这就是我想用我的程序做的,但是我找不到一种方法把它翻译成c++句子。如果有更好、更有效的方法来做我想做的事,请告诉我。
发布于 2014-11-19 14:24:00
我没有测试它,但这应该是可行的:
while( getline(myfile,line) )
{
if( line.find( codemp ) != string::npos )
{
cout << line << endl;
for( int i = 0; i < nbLines && getline( myfile, line ); ++i )
cout << line << endl;
}
}
它用一个while
迭代文件,并且当它find
字符串时,它打印"nbLines“其他行。
发布于 2014-11-19 14:13:38
既然你所拥有的是为你工作的,那么让我们先来看一看。在这里,我只对相关部分进行了跟踪,并添加了一个小部分。我们所需要做的就是在找到代码的情况下再打印四行代码,因此:
while (getline(myfile, line)) {
if (line.find(codemp) != string::npos) {
cout<<line<<endl;
getline(myfile,line);
found = true;
for (int i=4; i; --i) { <== new code begins
cout << line << '\n';
getline(myfile, line);
} <== new code ends
}
}
就这么简单。
https://stackoverflow.com/questions/27018640
复制相似问题