Reputation: 1017
#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 will remove all of the spaces in front of sentence. Postcondition: sentence has no spaces in front of the first word.
i want to take out words from a string sentence and get this error in c++
Error is -> String subscript out of range
Upvotes: 0
Views: 2137
Reputation: 2092
void extractFirstWord(string& sentence, string& word)
{
int i=0;
while(i<sentence.size() && sentence[i]!=' ') // i should be less than sentence size
{
i++;
}
word=sentence.substr(0,i);
sentence=sentence.substr(i);
}
Upvotes: 0
Reputation: 40145
use stringstream
#include <iostream>
#include <sstream>
int main(){
std::stringstream ss(" first second. ");
std::string word;
ss >> word;
std::cout << word << std::endl;//first
}
Upvotes: 0
Reputation: 3017
just consider the case when the input has no spaces, your variable i will increment till length of word and in that case it will be out of range. try to check whether i equals to length of word before the substr() method
Upvotes: 0
Reputation: 110658
In extractFirstWord
, you keep increasing i
if you haven't yet found a space. However, you might index past the end of the string if it's the last word in the string. Change the while
condition like so:
while(i < sentence.length() && sentence[i]!=' ')
Upvotes: 3