我對C++非常陌生,所以對於我可能會或可能不會明白的單詞很容易... 我們給出了一個字符串形式的段落,我們應該從字符串中獲取每個單詞並填充一個數組,顯示數組。我們今天瞭解了結構,所以這就是爲什麼我們應該輸出docWordCount(以及爲什麼可能出現錯誤的原因......)如何將單詞排序爲C++中的結構數組?
我想要做的是沿着字符串移動,直到找到空間,當我這樣做時,我使用.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] ==!')' –
你可以使用庫功能嗎?永遠不要重新發明輪子:http://coliru.stacked-crooked。com/a/5f53e32151af5465或者用'vector'代替所有'set'' – sehe
我想說如果text [i]是一個空格。我不知道這是否真的有效。我最初嘗試使用static_cast,但我不知道如果這工作或沒有,所以我嘗試了不同的 – user3470528