【发布时间】:2014-03-27 22:19:42
【问题描述】:
我对 C++ 很陌生,所以对我可能理解或可能不理解的词要轻描淡写... 我们得到一个字符串形式的段落,我们应该从字符串中获取每个单词并填充一个数组,然后显示该数组。我们今天了解了结构,这就是为什么我们应该输出 docWordCount(以及为什么它可能有问题......)
我要做的是沿着字符串移动,直到找到一个空格,然后使用 .substr 命令将单词复制到数组中。我最初尝试使用 static_cast 来查找是否有空格,我不确定问题是它不能那样工作,还是我做错了什么(可能是后者)。每次我沿着字符串移动时,我都会将字数增加 1,因此它会输出所有单词而不是它前面的内容。另外我应该提到,当我编译代码时,它会输出文本,然后给我一个“调试断言失败![...] 表达式:字符串下标超出范围。”另一个窗口中的错误。
#include <string>
#include <iostream>
using namespace std;
int main()
{
struct wordCount
{
string word;
int count;
};
wordCount docWordCount [500];
for(int i = 0; i < 500; i++)
{
docWordCount[i].word = "";
docWordCount[i].count = 0;
}
string text ="If there's one good thing that's come out of the European debt crisis\
it's that the U.S. has been able to shield itself from much of \
the mess. The sentiment will continue in 2012 as the U.S. \
economy is expected to grow faster than its European counterparts. \
That's according to the Organization for Economic Cooperation and \
Development which says the U.S. economy will expand at a 2.9% \
annual rate in the first quarter and then a 2.8% rate in the second quarter.";
cout << text << endl;
int wordLength = 0;
for(int i = 0; i < 500; i++)
{
if (text[i] == ' ' ) //if there isnt a space
wordLength++;
if (text[i] == !' ' ) //if there is a space
docWordCount[i].word = text.substr(i - wordLength, i);
}
for (int i = 0; i < 100; i++)
cout << docWordCount[i].word << endl;
return 0;
}
它应该是什么样子的
If
Theres
one
good
thing
等等...是我想要做的声音吗?有没有更简单的方法来解决这个问题?
【问题讨论】:
-
是否存在编码错误?我不熟悉空格字符的逻辑否定。代码为:
if (text[i] == !' ' ) -
你可以使用库功能吗?永远不要重新发明轮子:coliru.stacked-crooked.com/a/5f53e32151af5465 或将所有
set替换为vector -
我试图说明 text[i] 是否为空格。我不知道这是否真的有效。我最初尝试使用 static_cast,但我不确定它是否有效,所以我尝试了一些不同的方法
-
for sehe:我们还没有了解您链接中的第 24 行,我认为这是按字母顺序排序的。另外,istream_iterator 到底是做什么的?
-
!运算符将非零转换为0,将零转换为1。
标签: c++ arrays string structure