用来熟悉stl里string的用法,当程序中有to_string和stoi时,使用g++编译时会出现如下编译错误
error: 'stoi' is not a member of 'std'
,相关问题见https://stackoverflow.com/questions/38034197/compile-error-stoi-is-not-a-member-of-std
使用vs或更新版本的gnu(?)可以解决该问题
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string str[21];
int myfind();
string mycopy();
string add();
int n;
string mystring()//返回字符
{
string o;
cin >> o;
if (o == "copy")
return mycopy();
else if (o == "add")
return add();
else
return o;
}
int myfind()//返回数字,仅有可能是find和rfind的返回值
{
string order;
while (cin.peek() == ' ')
cin.get();
if (cin.peek() == 'f')
{
cin >> order;
string x = mystring();
int y = myfind();
return str[y].find(x);
}
else if (cin.peek() == 'r')
{
cin >> order;
string x = mystring();
int y = myfind();
return str[y].rfind(x);
}
else
{
int n;
cin >> n;
return n;
}
}
string mycopy()
{
int N = myfind(), X = myfind(), L = myfind();
return str[N].substr(X, L);
}
bool isnum(const string &s)
{
if (s.length() > 5)
return false;
else
{
for (int i = 0; i < s.length(); ++i)
{
if ('0' <= s[i] && s[i] <= '9');
else
return false;
}
}
return true;
}
string add()
{
string s1 = mystring(), s2 = mystring();
if (isnum(s1) && isnum(s2))
return to_string(stoi(s1, nullptr) + stoi(s2, nullptr));
else
return s1 + s2;
}
string& myinsert()
{
string S = mystring();
int N = myfind(), X = myfind();
str[N].insert(X, S);
return str[N];
}
void reset()
{
string s = mystring();
int n = myfind();
str[n] = s;
return;
}
void prints()
{
int n;
cin >> n;
cout << str[n];
return;
}
void printall()
{
for (int i = 1; i <= n; ++i)
cout << str[i] << endl;
return;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; ++i)
{
cin >> str[i];
}
string order;
cin >> order;
while (order != "over")
{
if (order == "insert")
myinsert();
else if (order == "add")
add();
else if (order == "print")
prints();
else if (order == "reset")
reset();
else if (order == "copy")
mycopy();
}
return 0;
}