我无法理解为什么我的代码没有改变输出文件的结果。我尝试使用“查找”成员函数来检查不正确的运算符,但它似乎没有改变结果。我如何检查字符串是否包含我正在寻找的字符串,然后替换它?
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void input(ifstream& inputfile, ofstream& outputfile, string& cpp);
void edit(ifstream& inputfile, ofstream& outputfile, string& line);
int main()
{
ifstream inputfile;
ofstream outputfile;
string line, cpp;
input(inputfile,outputfile,cpp);
edit(inputfile, outputfile, line);
}
void input(ifstream& inputfile, ofstream& outputfile, string& cpp)
{
cout << "Enter a cpp file to modify" << endl;
cin >> cpp;
cout << endl;
inputfile.open(cpp.c_str());
if (inputfile.fail())
{
cout << "File opening failed,did you enter your file name correctly?" << endl;
exit(1);
}
outputfile.open("cpp.txt");
}
void edit(ifstream& inputfile, ofstream& outputfile, string& line)
{
string a = "cin <<";
string b = "cout >>";
getline(inputfile,line);
while (! inputfile.eof())
{
line.find(a);
if (line == a)
{
outputfile << "cin >>";
}
line.find(b);
if (line == b)
{
outputfile << "cout >>";
}
else
outputfile << line << endl;
getline(inputfile,line);
}
}
答案 0 :(得分:0)
find()
在字符串中搜索指定的子字符串,然后返回其位置(如果找到),它不会修改正在搜索的字符串。您忽略了find()
的返回值。试试这个:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void input(ifstream& inputfile, ofstream& outputfile, string& cpp);
void edit(ifstream& inputfile, ofstream& outputfile, string& line);
int main()
{
ifstream inputfile;
ofstream outputfile;
string line, cpp;
input(inputfile,outputfile,cpp);
edit(inputfile, outputfile, line);
}
void input(ifstream& inputfile, ofstream& outputfile, string& cpp)
{
cout << "Enter a cpp file to modify" << endl;
cin >> cpp;
cout << endl;
inputfile.open(cpp.c_str());
if (!inputfile)
{
cout << "Input file opening failed, did you enter your file name correctly?" << endl;
exit(1);
}
outputfile.open("cpp.txt");
if (!outputfile)
{
cout << "Output file opening failed" << endl;
exit(1);
}
}
void edit(ifstream& inputfile, ofstream& outputfile, string& line)
{
string a = "cin <<";
string b = "cout >>";
while (getline(inputfile,line))
{
if (line.find(a) != std::string::npos)
{
outputfile << "cin >>";
}
else if (line.find(b) != std::string::npos)
{
outputfile << "cout >>";
}
else
outputfile << line << endl;
}
}
答案 1 :(得分:0)
我认为你的意图是:
if (line.find(a) != string::npos)
{
outputfile << "cin >>";
}
if (line.find(b) != string::npos)
{
outputfile << "cout >>";
}
答案 2 :(得分:0)
std::string::find()
没有更改字符串被调用。它试图找到作为参数发布的字符串或字符,并返回找到的字符的位置。您所要做的就是检查返回值是否等于std::string::npos
,这是一个值,表示未找到子字符串:
if (line.find(a) != std::string::npos) {
...
}
else if (line.find(b) != std::string::npos) {
...
}
此外,while (!eof())
通常被视为一种糟糕的编程习惯。改为在循环参数中执行输入:
while (std::getline(inputfile, line)) {
if (line.find(a) != std::string::npos) {
outputfile << "cin >>";
}
else if (line.find(b) != std::string::npos) {
outputfile << "cout <<";
}
else
outputfile << line << std::endl;
}