Reputation: 5
I've been working on a program my professor gave us awhile back and I've run into a logic issue, as in I can't figure out how to exactly do this. I need to output one word on each line of a sentence input by the user. For example, the user inputs "Hello World I'm Chris" and the program needs to output: Hello World I'm Chris
This is what I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int length;
cout << "Enter the sentence now." << endl;
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] != '\0')
{
cout << sentence[i];
}
else if(sentence[i] == '\0')
{
cout << endl;
}
}
system("pause");
}
However, when I run it, the program basically just outputs the same sentence. Is there another way I can do this? Many thanks.
Upvotes: 0
Views: 16630
Reputation: 57743
Your program outputs the same sentence because you told it to.
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] != '\0') // If the current char is not the end,
{
cout << sentence[i]; // print the character.
}
else if(sentence[i] = '\0') // This should be "=="
{
cout << endl;
}
}
Basically, you are printing each letter in the sentence back to std::cout
.
Please search StackOverflow for "C++ print word sentence", as many people have posted questions about this assignment.
Edit 1: The fundamentals of the assignment
The assignment requires you to extract letters from the input string to form a word. There are many ways to do this. Search your text book or reference manual for the std::basic_string
class and see what functions could help you.
Some people start from the first letter in the sentence and search for the next character that is not a letter:
const char valid_letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
sentence.find_first_not_of(valid_letters);
And they use the returned position to get a substring (std::string::substr) between the two positions.
Another approach is to use a loop. If the present character is a letter, append to the word
string.
Again search and see what examples you can find.
Upvotes: 0
Reputation: 636
Ok first of all with the code feel free to add in the input stuff you have in before!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence = "Hello World";
int length;
string temp = "";
for(int i = 0; i < sentence.length(); i++)
{
temp += sentence[i];
if(sentence[i] == ' ')
{
cout << temp << "\n";
temp = "";
}
}
std::cout << temp;
return 0; //*
}
Upvotes: 0
Reputation: 133
According to this the \0
does not represent a whitespace. It seems you want something more like:
[...]
if(sentence[i] == ' ') cout << endl; // check for whitespace
else cout << sentence[i];
[...]
By the way, due to the way markdown formats text, the 'one word per line' thing was not clear, I had to fake-edit your post to see what exactly you meant. I think using a code tag would solve that.
Upvotes: 1