• Advertisement
Sign in to follow this  

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

This topic is 4307 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
You're "pushing_back" the value of the first element of input_line (input_line[0]).

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Also, your type is "char", how do you expect to store a string in a single char?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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++

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement