Reputation: 33
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?
int main()
{
char string[]="Computer Science";
int l;
l=strlen(string);
char begin[l];
int i=0,ind=0;
while(string[i]!='\0')
{
begin[ind]=string[i];
if(string[i]==' ')
{
begin[ind]=NULL;
cout<<begin<<"\n";
ind=0;
//ind++;
i++;
}
else
{
ind++;
i++;
}
}
return 0;
}
Upvotes: 0
Views: 5196
Reputation: 310950
Variable Length Arrays (VLA) is not a standard feature of C++. Moreover there is no need to declare one more array that to output words separated by spaces.
Your program never outputs the second (or last) word in the string if there are no spaces after it.
And the program includes leading spaces in words because it does not skip spaces when there are more than one space between words.
The program can look the following way as it is shown in the demonstrative program.
#include <iostream>
int main()
{
char s[] = "Computer Science";
for ( const char *p = s; *p != '\0'; )
{
while ( *p == ' ' || *p == '\t' ) ++p;
if ( *p )
{
size_t i = 0;
while ( *p and not ( *p == ' ' || *p == '\t' ) )
{
++i;
++p;
}
std::cout.write( p - i, i ) << std::endl;
}
}
return 0;
}
The program output is
Computer
Science
For the condition
*p == ' ' || *p == '\t'
you could use a lambda expression. For example
auto is_blank = []( char c ) { return c == ' ' || c == '\t'; }
and then in loops you could write for example
while ( is_blank( *p ) ) ++p;
and
while ( *p and not is_blank( *p ) )
Or you could use standard C function isspace
declared in header <cstring>
to check the condition.
The task can be done using standard algorithms and iterators. For example
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
int main()
{
char s[] = "Computer Science";
std::istringstream is( s );
std::copy( std::istream_iterator<std::string>( is ),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>( std::cout, "\n") );
return 0;
}
The program output is the same as above that is
Computer
Science
Upvotes: 0
Reputation: 5741
Modern C++ offers a lot of features for handling strings. These features are designed to simplify handling string in more efficient way. Don't use C-Style string unless you have to. In your case, you could do
#include <iostream>
#include <string>
int main()
{
std::string str("Computer Science");
for(int i(0); i < str.size(); ++i){
if( str[i] == ' ' )
std::cout << '\n';
else{
std::cout << str[i];
}
}
std::cout << std::endl;
return 0;
}
With C++, you can do more reduction but I leave it as is.
Upvotes: 1
Reputation: 5287
You are looking only for space which printing output. Science has null after it not space. Change while to
while(i <= l)
Change your if condition to
if(string[i]==' ' || string[i] == '\0')
Upvotes: 0