Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- // Separate a sentence into words.
- int main()
- {
- string sentence; // User input.
- cout << "Enter a sentence." << endl;
- getline(cin, sentence); // Get the user's sentence.
- int space_location = 0; // Location of a space.
- int start_position = 0; // Begin a new word.
- int length = 0; // Length of the word.
- string word; // A word.
- cout << "Here is your sentence, one word at a time:" << endl;
- if (!sentence.empty()) // If the user entered a sentence,
- {
- // While there is a space in the sentence,
- while ( (space_location = sentence.find(" ", start_position)) != string::npos)
- {
- // Get the length of the word.
- length = space_location - start_position;
- // Get the word.
- word = sentence.substr(start_position, length);
- // Display the word.
- cout << word << endl;
- // This is the start of the next word.
- start_position = space_location + 1;
- }
- // If there are no more spaces,
- // Get the length of the last word.
- length = sentence.size() - start_position;
- // Get the last word.
- word = sentence.substr(start_position, length);
- // Display the last word.
- cout << word << endl;
- }
- else // If the user did not enter anything,
- {
- cout << "No sentence was entered." << endl;
- }
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement