473,388 Members | 1,220 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

reading txt file into class and inputting into a vector

Hi everyone. I am just starting out on my assignment on classes. We havent long learnt about them so I am struggling a little on how to do the following.

Below is a small part of the definition of the class.. I have not provided all of it as I dont have questions on the rest of it.... I was wondering how I am supposed to open a txt file in the class constructor target....

Expand|Select|Wrap|Line Numbers
  1. class target
  2. {
  3.    // Definition for class target
  4.    // Class target contains the internal logic for the game of target
  5.    // (user interaction is outside the class in application program)
  6.    //
  7.  public:
  8.    target();
  9.     // default constructor  
  10.     // Opens small default dictionary ("dict.txt") and reads words into 
  11.     // vector wordList
  12.     // Default dictionary contains only lower case words of length 4-9
  13.     // Sets centreLetter and otherLetters to spaces.
So far I have tried and failed. I know I have it wrong but I was hoping someone could point me in the right direction :-)

I will definately be asking my tutor for help this week in class but I would really like to make a start on it!

Expand|Select|Wrap|Line Numbers
  1. target :: target()
  2.     // default constructor  
  3.     // Opens small default dictionary ("dict.txt") and reads words into 
  4.     // vector wordList
  5.     // Default dictionary contains only lower case words of length 4-9
  6.     // Sets centreLetter and otherLetters to spaces.
  7.     {
  8.        ifstream infile;
  9.        string fname;
  10.        int data;
  11.        infile.open(fname.c_str()); 
  12.        if (infile.fail()) 
  13.        { 
  14.          cout << "File not found " << endl; 
  15.       return EXIT_FAILURE; 
  16.       }      
  17.       infile >> data;
  18.     }
Thx in advance
K.
Apr 5 '09 #1
15 6498
weaknessforcats
9,208 Expert Mod 8TB
First, your class description says that the default constructor opens a default dictionary "dict.txt" so I don't uinderstand why your constructor isn't doing that. Shouldn't it just open "dict.txt" ?

What you are doing is opening a file using a name contained in a local string object but you have failed to put a file name in that object.
Apr 5 '09 #2
when I make it the file name.. eg.
target :: target()
// default constructor
// Opens small default dictionary ("dict.txt") and reads words into
// vector wordList
// Default dictionary contains only lower case words of length 4-9
// Sets centreLetter and otherLetters to spaces.
{
ifstream infile;
string fname;
int data;
infile.open(fname."dict.txt");
if (infile.fail())
{
cout << "File not found " << endl;
return EXIT_FAILURE;
}
infile >> data;
centreLetter = ' ';
otherLetters = ' ';
}
it comes up with errors saying "aggregate 'std::ifstream infile' has incomplete type and cannot be defined..
expected unqualified -id before string constant
returning a value from a constructor
[Build Error] [target.o] Error 1

I am just stuck on what I am doing wrong...
Apr 6 '09 #3
newb16
687 512MB
1) - read doc on ifstream, note what headers you should include in order to use it ( fstream )
2) As you already noticed, the compiler probably pointed you to this line - fname."dict.txt" . This is not a valid expression.
3) return EXIT_FAILURE; . Yes, constructors don't return value. You can thrown an exception if something went wrong.
Apr 7 '09 #4
THank you :-) I didnt even think of that.. I got the first part to work .. or so it seems. it is at least compiling now... I really really appreciate it!!
Apr 7 '09 #5
Okay I just realised I am still doing it wrong. I need to obviously open dict.txt which I am now doing but it is reading into int data. I need it to read words into vector wordList.... how would I do that??? I have tried changing the part that says string data to vector<string> wordList but it doesnt like what I am doing?? any ideas? :-)

target :: target()
// default constructor
// Opens small default dictionary ("dict.txt") and reads words into
// vector wordList
// Default dictionary contains only lower case words of length 4-9
// Sets centreLetter and otherLetters to spaces.
{
ifstream infile;
string fname;
string data;
infile.open("dict.txt");
if (infile.fail())
{
cout << "File not found " << endl;
}
infile >> data;
centreLetter = ' ';
otherLetters = ' ';
}
Apr 8 '09 #6
weaknessforcats
9,208 Expert Mod 8TB
What is the format of your disc file? Are your words separated by spaces or by non-spaces, like a comma?

When you infile>>Astring, you get one word since the >> operator stops on whitespace. I would assume you could push_back to your vector right then. If the disc file uses comma separators, the you will need to use getline() so you can specify a comma delimiter. Here you use a char buffer with getline() and on the next line you assign the buffer to a string and then push_back the string to your vector.
Apr 8 '09 #7
You guys are all so helpful :) But me being me keeps confusing myself. I know it is probably such a simple thing to do...

I did a test doing the following

for (int i = 0; i <= 100;i++)
{
infile >> data;
cout << data << endl;
}

cout << "this is data outside the loop " << data;

When it does this it seems to output each string up to 100 in the loop which is what I would expect it to do and if I just ask it to output data outside the loop it outputs the last string. That makes sense...

But as soon as I add the vector wordList when I run it the executable opens and closes so quickly I dont know what I am doing wrong...

for (int i = 0; i <= wordList.size(); i++) // I have made it <= as the vector size is 0 and the loop will not run if I say if int i < vector size will it??
{
infile >> wordList.at(i);
wordList.push_back(i);
cout << wordList.at(i) << endl;
}

Am I still off track or almost there??? I know it is probably something sooo simple.. but I just dont understand why it isnt working as a vector...
Apr 8 '09 #8
ok I worked it out.. although it is a little manual :) so dont worry about answering the previous question... YAY I did something on my own :)
Apr 9 '09 #9
ok my next question is about calling a function into the test.cpp file... for some reason a different function is not working. Am I calling it wrong?????

I

int main()
{
string fname;
cout << "\t Welcome to Target Helper \n\n";
target t; // create a new target object
char choice = ' ';

while (choice != 'Q')
{
printMenu();
cin >> choice;
// convert choice to to uppercase
choice = toupper(choice);
// ... !
switch (choice)
{
case('N') : t.newGame();
//break;
.................................................. .


My class function (implementation file) is very basic.. I just want to get it working before I add the algorithms.

So I have just done as below... it seems the problem is coming from the main.cpp file though.......??

void target::newGame(char centre, string others)
// pre : none
// post : set centre letter and other letters for a new game of target
{
cout << "Enter centre letter : ";
}

the error message showing is
no matching function for call to 'target::newGame()'
candidates are: void target::newGame(char, std::string)
[build error][puzzle.o] Error 1
Apr 9 '09 #10
ooh I worked it out :-)
Apr 9 '09 #11
weaknessforcats
9,208 Expert Mod 8TB
ok I worked it out.. although it is a little manual :) so dont worry about answering the previous question... YAY I did something on my own :)
You aren't by any chance using Visual Studio.NET? I mean you mention the thing opening and closing so fast you couldn't read the output.

If so, Visual Studio.NET has two kinds of builds: Debug (the default) and Release.

The Debug build .exe has code in it to support the debugger. When you Start the program, Visual Studio sees it is a debug .exe and ASSUMES you are using your debugger and that you have already installed the necessary breakpoints to halt the code. If you are not using the debugger all you see is a black flash as your program goes in and out of execution.

Instead of Start, if you select Start Without Debugging, you are telling Visual Studio that while this is a debug .exe you are not using your debugger. In thie case, Visual Studio will halt execution at the end of main() with "Press any to continue...".

That is, you don' need to add code at the end fo main() to halt the program.
Apr 9 '09 #12
No I'm using bloodshed dev c++. I got everything I was asking sorted out. although I kind of made it manual by getting it to read in the exact number of words in the file.. I was stuck on how to change it.....

Anyway now I'm onto the harder stuff... but I dont think I will work on it today. I will probably have a few questions where I am stuck but I want to see if I can do it on my own :-)
Apr 10 '09 #13
okay so now I am trying to work out in my assignment on how to output each character in a string... I understand what I am doing wrong in this but I am not sure how to make it right??

string c;

for (int i = 0; i < wordList.size(); i++)
{
c = wordList.at(i);
for (int j = 0; j < c.length(); j++)
{
int sum = 0;
char k;
sum = sum + c.length();
k = c.at(j);
if (k == centreLetter) //why is this comparison resulting in my program crashing?
{
cout << c << endl;
}
}
}
Apr 13 '09 #14
ok dont worry about the previous thread. I managed towork it out... it has taken me a while.. but I am getting there and it is helping me to understand it all..

Now I am stuck on a merge sort.. I think I might give myself a break for the night after I post this as I have been working on it for hours.........

okay so I have sorted each character vector into ascending order and now I need to merge them. well sort of..

I have two vectors.. one that contains the letters the user enters (lets call it userlist) (there are 9 in total) and then another vector which contains the "dict.txt" list.

Basically I need to check the dict vector against the userlist vector. If all the characters in userlist vector are used up then I need to output the string.
Does that make sense? Would I use a merge sort for that?????? I dont know if I need to??

anyway here is the mergesort code I have been working on but it seems to be crashing so im not 100% sure what I am doing wrong

vector <char> result;
int left = 0 ; // index for c
int right = 0 ; // index for otherletters
while ( left < c.size() && right < otherLetters.size())
{
if (c.at(left) < otherLetters.at(right))
{
result.push_back(c.at(left));
left++;
}
else
{
result.push_back(otherLetters.at(right));
right++;
}
for (int i = left ; i < c.size();i++) // i think the error is here somewhere...?
result.push_back(c.at(i));
for (int i = right ; i < otherLetters.size(); i++)
result.push_back(otherLetters.at(i));

}
for (int i = 0; i < result.size(); i++)
{
cout << result.at(i);
}
cout << endl;
}

thanking you all again for your help :) it really has helped me work through my assignments. especially when it is hard to get help from my classes.
Apr 14 '09 #15
does anyone have any ideas I'm stuck on comparing the two strings..

Basically I have one string and a vector of characters.
I have sorted both in ascending order. basically I need to output the string if all of the characters in it match some or all of the characters from the vector.
eg
vector characters is airport
string is
airport
output airport
or vector characters is airport
string is air
output air

I know it is probaby something simple but I cant work out how to do it?
I have written up a code and am erasing the character from the string when ther is a match but the thing I am finding is that I know I have it wrong but I dont know how to fix it... can someone help??

int sum = 0;
sum = c.length(); // this is the string from the txt file

for (int h = 0; h < c.length(); h++)
{
if (c.at(h) == otherLetters.at(h))
{
sum--;
c.erase(h, 1);
// cout << c1 << endl; //this is the string when it isnt sorted
// cout << c << endl; //this is the sorted string
// cout << otherLetters.at(h) << endl; //this is the sorted vector
// if (sum == 0) // sum never is 0.. I have made an error somewhere in the above loop but I'm stuck..
// {
// cout << "this is the output " << c1 << endl; //cant even get to this point.
// }
Apr 16 '09 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Santah | last post by:
hi I'm new to C++ and I'm currently working on Visual C++ 6.0 I'm trying to open a text file, and read some data from it part of the text file looks like this: --------
4
by: nightflyer | last post by:
Hi all, [code snippet appended at the end.) my question: A class has a few string variables with not know length at design time. Now I declare lets say a 1000 of those classes and put them...
0
by: Eric Lilja | last post by:
Hello, I have a text file that contains a number of entries describing a recipe. Each entry consists of a number of strings. Here's an example file with only one entry (recipe): Name=Maple Quill...
4
by: Mark Stijnman | last post by:
A while ago I posted a question about how to get operator behave differently for reading and writing. I basically wanted to make a vector that can be queried about whether it is modified recently...
6
by: Dave Reid | last post by:
Hi everyone... I'm pretty much a newbie C++ user, and I've run into a problem. I'm trying to read in a large text file, and then do manipulations on it. I can read it into a large 2-dimensional...
2
by: saltedcoffee | last post by:
hey, I am beginer to C++ programing. I am working on a project called the "maze Problem" First of all I am required to read a text file in( which is the maze) and store it into a 2 dimentional...
5
by: Steevee | last post by:
Hi all! A quick question to which i'm not sure if there is an answer without changing all my code, which i'm not going to do at this point :p... i'm inputting data to a struct, and a vector...
9
by: Eric Lilja | last post by:
Hi! I have a program with a class that needs to be able to write itself to a file in clear text format. The file has two integers and vector of struct objects. The struct has a string that can...
15
by: arnuld | last post by:
This is the partial-program i wrote, as usual, i ran into problems halfway: /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a function to open a file for input and then read...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.