我的应用程序出现此问题。当我的应用程序运行8-13次而不是1次时。
我的程序的主要目的是使用(filein)
从文件string strTemp2
中搜索一行,将其加载到临时字符串并将其替换为string strTemp2 + "\t\t"+"test"
到{{1 }}
fileout
用于此目的的输入文件(c:/hospitaldata/PatientDatabase.txt):
string strReplace = strTemp2;
string strNew = strTemp2+"\t\tTest";
ifstream filein("c:/hospitaldata/PatientDatabase.txt"); //File to read from
ofstream fileout("c:/hospitaldata/PatientDatabaseTEST.txt"); //Temporary file
if (!filein || !fileout)
{
cout << "Error opening files!" << endl;
return 1;
}
string strTemp;
//bool found = false;
while (filein >> strTemp)
{
if (strTemp == strReplace){
strTemp = strNew;
//found = true;
}
strTemp += "\n";
fileout << strTemp;
//if(found) break;
}
我现在生成的输出文件是:
CPR Patient nr Værelse nr Seng nr Medicin
140143211 256 6 5
我想要生成的文件(c:/hospitaldata/PatientDatabaseTEST.txt)
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
140143211 256 6 5 Test
答案 0 :(得分:0)
读取行,而不是单词:
#include <iostream>
#include <sstream>
using namespace std;
void markTest(istream & input, ostream & output, const string & pattern) {
string strTemp;
while (std::getline(input, strTemp))
{
if (strTemp == pattern){
strTemp += "\t\tTest";
}
output << strTemp << "\n";
if (!output) {
break;
}
}
}
int main() {
istringstream input(
"CPR Patient nr Værelse nr Seng nr Medicin\n"
"140143211 256 6 5");
markTest(input, cout, "140143211 256 6 5");
return 0;
}
答案 1 :(得分:-1)
如果你想要循环一次,你必须在if条件中放置一个中断。
while (filein >> strTemp)
{
if (strTemp == strReplace){
strTemp = strNew;
break; // breaking the loop
//found = true;
}
strTemp += "\n";
fileout << strTemp;
//if(found) break;
}
答案 2 :(得分:-1)
您可以在循环的每个循环中写入输出文件,而不仅仅是在找到匹配项时。这应该有效:
string strReplace = strTemp2;
string strNew = strTemp2+"\t\tTest";
ifstream filein("c:/hospitaldata/PatientDatabase.txt"); //File to read from
ofstream fileout("c:/hospitaldata/PatientDatabaseTEST.txt"); //Temporary file
if (!filein || !fileout)
{
cout << "Error opening files!" << endl;
return 1;
}
string strTemp;
filein.getline(strTemp);
fileout << strTemp << std::endl;
//bool found = false;
while (filein >> strTemp)
{
if (strTemp == strReplace){
strTemp = strNew;
strTemp += "\n";
fileout << strTemp;
//found = true;
}
//if(found) break;
}