【发布时间】:2016-06-14 08:28:31
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";
for (int i = 0; i < len; i++)
{
if(s[i] != ' ')
{
counter++;
}
if(s[i] == ' ' || i == len - 1)
{
if(counter > max_word)
{
max_word = counter;
//handling end of string.
if(i == len - 1)
max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
else
max = s.substr(i - max_word, max_word);
}
counter = 0;
}
}
cout << max_word << " " << max << endl; #output
return 0;
}
输入字符串“This is cool”时,当前输出为“4 This”。 如何让它打印 '4 This;凉爽的' ? 通过终端在Linux中运行它,它给了我错误 " 抛出 'std::out_of_range' 实例后调用终止 what(): basic_string::substr Aborted (core dumped) "
【问题讨论】:
-
你想输出最大长度的所有单词吗?
-
是的,我希望我的程序打印字符串中所有最大长度的单词。
-
你为什么要这样格式化你的代码?为什么在展示给其他人之前至少不整理一下?为什么您不至少在将其展示给其他人之前对其进行整理,以便他们可以帮助您修复它??
-
@PreferenceBean:因为那会花很长时间,而且无论如何你都会得到答案,而且因为现在阅读和写作已经成为消亡技能,所以看起来:(
-
@ChristianHackl:这就是为什么我希望像弗拉德这样的人不要回答这样的问题。