【发布时间】:2020-03-23 04:06:57
【问题描述】:
我正在为我的第一个 c++ 课程的作业而苦苦挣扎。我希望有人可以在正确的方向上帮助我。我需要在 c 字符串中编写一个“strlen 的递归版本”。根据我的讲义,我的函数应该是这样的,“int str_length(char s[])”。
我的主要问题是试图让用户输入一个长度不确定的字符串或 cstring 并将其用于函数调用。我真的很感激我能得到的所有帮助和指导。
我已经玩了很多次我的代码,以至于我迷失了方向。看来我会解决一个问题并创建一个新问题。我认为我的函数编写正确,但如果有更好/正确的方法,这里是代码。
#include <iostream>
#include <cstring> //included both until I find my solution
#include <string>
using namespace std;
//string or char sentence; This part of my struggle
char choice = 'Y';
int str_length(char s[]);
int main()
{
while ((choice != 'n') && (choice != 'N'))
{
cout << "Enter a sentence. ";
//user entry cin, getline etc
cout << sentence;
//cout << str_length(sentence);
cout << endl;
cout << "Do you want to have another run? Y/N ";
cin >> choice;
}
}
int str_length(char s[])
{
// if we reach at the end of the string
if (s == '\0')
{
return 0;
}
else
{
return 1 + str_length(s + 1);
}
}
【问题讨论】:
-
当代码按预期工作时,为什么你还在苦苦挣扎?有什么问题?
-
你是在问std::getline()怎么用?
-
是您得到“错误”长度的问题,例如“这是一个包含多个单独单词的句子,cout 只会读取第一个单词,而您应该使用 getline 读取整行” ?如果是,您应该在问题中提及这一点
-
cin >> sentence;不起作用。具体来说,它会一直读取到第一个空格。该错误不在显示的代码中。您可能希望按照上面 cmets 中的建议使用std::getline()。 -
为什么你的标题是“strlen 的递归版本”,而你的问题却与此完全无关?错误识别问题的问题是人们会搜索“strlen 的递归版本”,并遇到与读取输入有关的线程。
标签: c++ string recursion c-strings