[英]C++ substring error
So, I made a program that will let a user enter a command, like print message
and it will show him the message he entered. 因此,我制作了一个程序,该程序可以让用户输入命令,例如
print message
并向他显示他输入的消息。 For example, if he types in: print Hello
, the console's output will be Hello
. 例如,如果他输入:
print Hello
,则控制台的输出将为Hello
。
Now, here's my code: 现在,这是我的代码:
#include <iostream>
using namespace std;
int main()
{
string command;
start:
cout << ">>> ";
cin >> command;
if (command.substr(0,5) == "print")
{
if (command.substr(6,command.end) != "")
{
cout << command.substr(6,command.end);
goto start;
}
else
{
cout << "Usage: print text";
goto start;
}
}
}
The thing is I get an error: 事情是我得到一个错误:
no matching function for call to 'std::basic_string::substr(int, )'|
没有匹配的函数可以调用'std :: basic_string :: substr(int,)'|
and I'm not sure if I specified the substring length correctly. 并且我不确定是否正确指定了子字符串的长度。 I wanted the first if to check if the first five words were
print
. 我想先检查一下是否
print
了前五个字。
Try replacing command.end
with command.length()
. 尝试将
command.end
替换为command.length()
。
Sidenote: It is good programming style to use the break, continue, and return statements instead of the goto statement whenever possible. 旁注: 良好的编程风格是尽可能使用break,continue和return语句代替goto语句。
Your error is that you are providing command.end
as an argument to the substr
function which is not a valid parameter. 您的错误是您将
command.end
作为substr
函数的参数提供,该参数不是有效参数。 It looks like you want to print the rest of the contents of command
, in which case you can just call command.substr(6)
. 看起来您想打印出
command
的其余内容,在这种情况下,您只需调用command.substr(6)
。
First of all, you forgot to write #include <string>
. 首先,您忘记编写
#include <string>
。 Also it would be better not to use goto
operator and a lot of magic numbers (5, 6 in your code). 另外最好不要使用
goto
运算符和很多幻数 (代码中的5、6)。 For reading string (from standard input) that can contain spaces you should use getline . 为了从标准输入中读取可以包含空格的字符串,您应该使用getline 。 In
substr
you omit the second argument if we want to get all characters until the end of the string . 在
substr
,如果我们要获得所有字符直到字符串末尾,则省略第二个参数。
I have refactored your solution and have the following code: 我已经重构了您的解决方案,并具有以下代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string command;
string prompt("print");
cout << ">>> ";
while(getline(cin, command) &&
command.size() >= prompt.size() &&
command.substr(0, prompt.size()) == prompt)
{
if (command.size() > prompt.size())
{
cout << command.substr(prompt.size() + 1) << endl;
}
else
{
cout << "Usage: print text" << endl;
}
cout << ">>> ";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.