Need help in assigning char values to a deque...

Started by
3 comments, last by vrok137 17 years, 11 months ago
I am having some trouble in assigning and printing values from a deque list (if that is the correct way of saying it). Here's what the program should be doing; it reads a text file with a bunch of words in it, the first word being "Aarhus". It then stores all these values in elements of a deque container named d1. Last, it calls the first element and prints it to the console screen. Here is the problem I am encountering. Although the whole program compiles correctly, all it displays as the first element is "A" when it should actually be "Aarhus". It would be nice if someone was to help in explaining why this is happenning or other alternatives. Below is the source code to my program: Language: C++

#include <iostream>
#include <string>
#include <fstream>
#include <deque>
#include <algorithm>

using namespace std;

int main()
{
	deque<char> d1;
	char input_line[50];// this will contain the data read from the file
	ifstream file_in("words.txt");

	if(!file_in)//if an error occurs
	{
		cout << "ERROR, FILE COULD NOT BE OPENED!";
		return -1;
	}

	while(!file_in.eof())// while the file has not reached the end
	{
		file_in.getline(input_line, 49); // gets a line of text from the file
		d1.push_back(*input_line);// stores the value as an element to d1
	}

	cout << d1.at(1); // should print a word like "Aarhus"
	                  // but instead, all it prints is "A"
	cin.get();

	return 0;
}

-Thanks in Advance
Advertisement
You're "pushing_back" the value of the first element of input_line (input_line[0]).
Also, your type is "char", how do you expect to store a string in a single char?
That's because deque<char> holds single characters. You might want to change that to deque<std::string> or deque<char*>, although I'm not sure if char* are going to work.
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)
Thanks guys! I figured it out!

Like deathcrush said, all I had to do was declare deque as:
deque<std::string> d1;

I also had to take the * off of input_line in the push_back() call.

:D++

This topic is closed to new replies.

Advertisement