Z ee Z ee - 18 days ago 7
C++ Question

How to separate words from a sentence (only using character arrays and no built-in c++ functions)?

I wrote this code to separate words from a sentence. I have to use character arrays(no strings) and can't use any built-in function(restricted by instructor). This does not work .

#include<iostream>
using namespace std;
int main()
{
char sentence[100]={'\0'}, word[100]={'\0'};
cin.getline(sentence,100);
for(int i = 0; sentence[i] != 32 || sentence[i] != '\0'; i++)
{
word[i]=sentence[i];
}
cout << word;
}

Answer

I think you'd like to separate all of the words in this sentence, so you can't make loop stop when it meet first blank.

#include<iostream>
using namespace std;
int main()
{
  char sentence[100]={'\0'}, word[100]={' '};
  cin.getline(sentence,100);
  for(int i = 0; sentence[i] != '\0'; i++)
  { 
    word[i]=sentence[i];
  }
  cout << word;
}

Above code may can help you.

Comments