Duncan said:
I wish to insert a movie title into a char array (e.g Indiana Jones
and the Last Crusade) However all i am getting when I output is
Indiana.
I have declared the array
char Title[50];
That's an array of individual characters.
This gets a sequence of characters from the standard input, and stops on
white space.
but all I get when I cout << Title is Indiana.
"Indiana" is the sequence of characters you just read: 'I', 'n', 'd'...
I want to make it so Title[0] is Indiana, Title[1] is Jones ...etc
For that, Title would have to be an array of strings, where each string
is a separate sequence of characters.
Is this possible any help would be appreiciated.
Thanks in Advance.
Instead of a raw array of characters, you seem to need a sequence of
strings. Instead of using raw arrays, consider using a std::string to
represent each word in the movie title, and a std::vector to hold the
sequence of strings. You then would have the option of looping over the
input, getting one word at a time. Alternatively, you could use the
std::copy algorithm and std::istream_iterator to avoid the explicit
looping. Here's a combination of these approaches that gets one title
per line of input; I've overloaded the insertion & extraction operators
(<< and >>) as well, since I think it makes the intent of each block of
code clear.
#include <iostream>
#include <string>
#include <vector>
typedef std::vector< std::string > Title;
std::istream& operator >> ( std::istream& input, Title& title );
std:
stream& operator << ( std:
stream& output, Title& title );
int main ( )
{
Title title;
while( std::cin )
{
std::cin >> title;
std::cout << title;
}
}
#include <algorithm>
#include <iterator>
#include <sstream>
std::istream& operator >> ( std::istream& input, Title& title )
{
title.clear( );
std::string line;
std::getline( input, line );
std::stringstream line_stream( line );
std::copy( std::istream_iterator< std::string >( line_stream ),
std::istream_iterator< std::string >( ),
std::back_inserter( title ) );
return input;
}