C++ 每次字符串通过时递减值

C++ Decrease value every time string passes

本文关键字:过时 字符串 C++      更新时间:2023-10-16

我正在努力找到一种方法来减少每次显示字符串时字符串中的值。

使用以下代码,考虑文本文件的第一行是some text #N#N应替换为从 18 减少到 1 的数字。当它达到 0 时,它应该回到 18。

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void find_and_replace(string & source, string const & find, string const & replace)
{
for (string::size_type i = 0; (i = source.find(find, i)) != string::npos;) {
source.replace(i, find.length(), replace);
i += replace.length();
}
}
int main(int argc, char * argv[])
{
std::ifstream fileIn("Answers.txt", std::ios::in | std::ios::binary);
string question;
string line;
if (!fileIn) {
cout << "Cannot open input file!" << endl;
return 1;
}
while (getline(fileIn, line)) {
if (line == "The answer can be found in a secret place in the woods.") {
fileIn.clear();
fileIn.seekg(0, ios::beg);
}
cout << "Ask a question followed by the Enter key. Or type 'exit' to Exit program.n";
getline(cin, question);
system("CLS");
find_and_replace(line, "#N", "18");
if (question == "") {
cout << "Your input cannot be blank. Please try again.nn";
}
else if (question == "exit")
exit(0);
else {
cout << "Q: " + question
<< "nA: " + line + "nn";
}
}
}

此代码仅将#N更改为18,仅此而已。

请帮助伙计们。

您已将值硬编码为 18,并且没有任何递减数字的代码。

尝试这些更改

把它放在主的开头

int tempVar=18;
char buffer[100];

并替换

find_and_replace(line, "#N", "18");

sprintf(buffer,"%d",tempVar--)
if(tempVar<0)
tempVar=18;
find_and_replace(line, "#N", buffer);

https://www.programiz.com/cpp-programming/library-function/cstdio/sprintf

你可以使用如下的东西:

#include <sstream>
#include <string>
class Replacer
{
const std::string token_;
const int start_;
int current_;
public:
explicit Replacer(const std::string & token, int start)
: token_(token), start_(start), current_(start)
{
}
std::string replace(const std::string & str)
{
const std::size_t pos = str.find(token_);
if (pos == std::string::npos)
return str;
std::string ret(str);
std::ostringstream oss;
oss << current_;
ret.replace(pos, token_.size(), oss.str());
--current_;
if (current_ == 0)
current_ = start_;
return ret;
}
};

然后你可以像这样使用它:

std::string examples[] = {
"",
"nothing",
"some number #N",
"nothing",
"some other #N number",
"nothing",
"#N another test",
"nothing",
};
Replacer replacer("#N", 18);
for (int i = 0; i < 8; ++i)
std::cout << replacer.replace(examples[i]) << 'n';