#include<iostream>
#include<string>
using namespace std;
void extractFirstWord(string& sentence, string& word);
void processBlanks(string& sentence);
int main() {
string sentence, word;
cout << "Input a sentence: ";
getline(cin, sentence);
while (sentence != "") {
processBlanks(sentence); // removes all blanks from the front of sentence
if (sentence.length() > 0) { // removing blanks may have made sentence null - cannot extract from a null string
extractFirstWord(sentence, word); // gets first word from sentence and puts into word
cout << word << endl; // output one word at a time
}
}
system("PAUSE");
return 0;
}
void extractFirstWord(string& sentence, string& word)
{
int i=0;
while(sentence[i]!=' ')
{
i++;
}
word=sentence.substr(0,i);
sentence=sentence.substr(i);
}
// extractFirstWord removes the substring of sentence
// from the beginning to the first space from sentence
// and stores the same string into word. sentence is
// shortened accordingly.
// Postcondition: sentence is shortened, and word
// is appropriately the first word in
// sentence.
void processBlanks(string& sentence)
{
int i=0;
while(sentence[i]==' '){i++;}
sentence=sentence.substr(i);
}
processBlanks は、文の前のスペースをすべて削除します。事後条件: 文の最初の単語の前にスペースがありません。
文字列文から単語を取り出して、C++でこのエラーを取得したい
エラーは -> 文字列添え字が範囲外です