473,322 Members | 1,473 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,322 software developers and data experts.

Reading in a file to an array

In my program I need to read in a file, search for 100 unique words, and count how many times a found word has been found all by using an array. This is what I have so far, but when the file is found it simply returns zero.

please any help would be great

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std; 
  5. const int LIST_SIZE = 100;
  6.  
  7. struct WordInfo
  8. {
  9.     string theWord;
  10.     int multi;
  11. };
  12.  
  13.  
  14. bool openFile(ifstream &inf)
  15. {
  16.     string fileName;
  17.     cout << "Please enter the file: ";
  18.     cin >> fileName;
  19.  
  20.     inf.open(fileName.c_str());
  21.  
  22.  
  23.  
  24.     if (!inf.is_open())
  25.     {    
  26.         cerr << "File couldnt be found ";
  27.         cout << endl;
  28.         exit(-1);
  29.         return false;
  30.  
  31.     }
  32.     else
  33.         return true;
  34.  
  35. };
  36.  
  37.  
  38.  
  39. bool readWord(ifstream &inf, string &word)
  40. {
  41.     if (inf >> word)
  42.     {
  43.         return true;
  44.     }
  45.     return false;
  46. };
  47.  
  48. int lSearch(WordInfo list[], int items, string key)
  49. {
  50.     int idx;
  51.     for (idx=0; idx < items && list[idx].theWord !=key; idx++); 
  52.  
  53.     if (idx==items)
  54.         return (-1);
  55.     return(idx);
  56.  
  57. };
  58.  
  59. bool readWords(WordInfo wordList[], int &numWords)
  60. {
  61.     ifstream inf;
  62.     if (!inf.is_open())   // openFile returns false if file not opened
  63.     return(false);
  64.  
  65.     numWords=0;
  66.     string tempWord;
  67.  
  68.     while (numWords<LIST_SIZE && readWord(inf,tempWord)) 
  69.     {
  70.   // readWord returns true if a word is read, false if end of file
  71.     int idx=lSearch(wordList, numWords, tempWord); 
  72.  
  73.     // check idx and either place tempWord into the array at the next
  74.     //  open slot or use idx to increment the found word's count
  75.     // (don't forget to increment numWords, too).
  76.     // IF TEMPWORD=FOUND, ++ WORD COUNT, IF TEMPWORD=NEWWORD, ADD TO ARRAY IN NEXT SPOT
  77.  
  78.  
  79.  
  80.     }
  81.  
  82.   return true;
  83. };    
  84.  
  85. void sortText(WordInfo list[], int items)
  86. {
  87.     int spot;
  88.  
  89.     for(spot =items-1; spot>0;spot--)
  90.     {
  91.         int idxMax=spot;
  92.             for (int idx=0; idx<spot; spot++)
  93.                 if(list[idx].theWord>list[idxMax].theWord)
  94.                     idxMax = idx;
  95.             if (idxMax!=spot)
  96.                 swap(list[idxMax],list[spot]);
  97.     }
  98.  
  99. };
  100.  
  101.  
  102.  
  103.  
  104. int main()
  105. {
  106.  
  107.     WordInfo arr[LIST_SIZE];
  108.  
  109.     ifstream inf;
  110.     int x = 0;
  111.     string word;
  112.     openFile(inf);
  113.     cout << readWord(inf, word) << endl;
  114.     lSearch(arr, x, word);
  115.     readWords(arr,x);
  116.  
  117.  
  118.  
  119.  
  120.  
  121.     return 0;
  122. }
Sep 11 '07 #1
4 2244
arnaudk
424 256MB
It doesn't look like you tried very hard to find which part of your program wasn't working as you expected. Also, as is written in the "reply guidelines" to the right of the box in which you typed your question, enclose your code between code tags to make it easier to read. The abundance of empty lines doesn't help either.

Why do you spread your error message over stderr and stdout streams?
Expand|Select|Wrap|Line Numbers
  1. // No:
  2. cerr << "File couldnt be found ";
  3. cout << endl;
  4. // Yes:
  5. cerr << "File couldnt be found " << endl;
  6.  
Why write so many trivial functions? Maybe it would be better to write a smaller number of more meaningful functions. What do you mean by "the file simply returns zero"? If you mean that your program prints zero as the output, then take a look at your main()
Expand|Select|Wrap|Line Numbers
  1. cout << readWord(inf, word) << endl;
  2.  
Given your definition of readWord, the fact that it returns zero should tell you that inf >> word failed which in turn should tell you that either inf.good() is false or that no space-delimited words were found in the file stream inf. Why don't you write some code to figure which of these is the case?
Sep 11 '07 #2
I have gotten the program to read the words of the file, however, I think there are errors in my code to keep track of multiplicity of the word or add it to a new index
Expand|Select|Wrap|Line Numbers
  1. bool readWords(WordInfo wordList[], int &numWords)
  2. {
  3.     ifstream inf;
  4.     if (!openFile(inf))   // openFile returns false if file not opened
  5.         return(false);
  6.  
  7.     numWords=0;
  8.     string tempWord;
  9.     int idx;
  10.  
  11.     while (numWords<LIST_SIZE && readWord(inf,tempWord)) 
  12.     {
  13.   // readWord returns true if a word is read, false if end of file
  14.      idx=lSearch(wordList, numWords, tempWord);
  15.     // check idx and either place tempWord into the array at the next
  16.     //  open slot or use idx to increment the found word's count
  17.     // (don't forget to increment numWords, too).
  18.     if (!idx==-1)
  19.     {
  20.         tempWord = wordList[idx].theWord;
  21.         numWords++;
  22.     }
  23.     else    
  24.         wordList[idx].multi++;
  25.  
  26.     }
  27.  exit(idx);    
  28.  return true;
  29. };    
the program is supposed to find 100 unique words and keep track of any repeating ones. Also, when I allow an input for the filename as opposed to hardcoding it, the program doesn't open the file but rather goes back into the function and tells me it cant find it:
Expand|Select|Wrap|Line Numbers
  1. bool openFile(ifstream &inf)
  2. {
  3.     //string fileName;
  4.     //cout << "Please enter the file: ";
  5.     //cin >> fileName;
  6.  
  7.     inf.open("C:\\Documents and Settings\\Owner\\Desktop\\test.txt");
  8.  
  9.     if (!inf.is_open())
  10.     {    
  11.         cerr << "File couldnt be found ";
  12.         cout << endl;
  13.         exit(-1);
  14.         return false;
  15.         }
  16.     else
  17.         return true;
  18. };
Sep 11 '07 #3
arnaudk
424 256MB
You're still not using [CODE=cpp]...[/code] tags properly.

So what is your question about the word counting part of your code?

As for the filename, I suspect you're not escaping the slashes \ when you input the filename from the prompt. How about cin >> fileName; then cout << fileName << endl; to confirm it's as you expect it? Try to put the file in the current directory so you don't have to specify a path. Also, if you use cin several times, you'll have to call cin.clear(); to clear the input buffer of any junk before reusing it.

A general note, it seems you're not really debugging your code. If it doesn't behave as you expect it to, have a look at what values your variables are holding by sending them to cout. Simplify your code by commenting out sections until you get a section to do what you expect then gradually uncomment out more and more functionality until you pinpoint what it is exactly which is causing you problems. Instead of a filestream, make a stringstream of words to test with, for example;

Expand|Select|Wrap|Line Numbers
  1. string teststr = "some words to search through for testing";
  2. stringstream ss(teststr);
  3. string word;
  4. while (ss >> word) {
  5. cout << word << endl;
  6. }
  7.  
Sep 11 '07 #4
sicarie
4,677 Expert Mod 4TB
jla1357-

Please read your Private Messages (PM's), which are accessible via the PM link in the top right corner of the page. Thanks!
Sep 11 '07 #5

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

Similar topics

6
by: Foxy Kav | last post by:
Hi, another question from me again, i was just wondering if anyone could give me a quick example of reading data from a file then placing the data into an array for some manipulation then reading...
3
by: Nick | last post by:
I have found a class that compresses and uncompresses data but need some help with how to use part of it below is the deflate method which compresses the string that I pass in, this works OK. At...
10
by: T Cordon | last post by:
I am using a StreamReader to read text from an HTML file and display it as part of a page in a Label Control. Buy it is not displaying characters as: ñ, ó, ú, etc. Please Help. Thanks
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
29
by: yourmycaffiene | last post by:
Okay, this if my first post so go easy on me plus I've only been using C for a couple of weeks. I'm working on a program currently that requires me to read data from a .dat file into a 2d array and...
10
by: nuke1872 | last post by:
Hello guys, I have a file names network.txt which contains a matrix. I want to read this matrix as store it as an array. I am new to stuff like these...can anybody help me out !! Thanks nuke
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
2
by: GeoUK | last post by:
Hi All, New member here with a bit of problem. I have read the FAQ's and searched text books but still cannot solve the problem that I have. As part of a course I am doing at University I had...
0
by: Anish G | last post by:
Hi, I have an issue with reading CSV files. I am to reading CSV file and putting it in a Datatable in C#. I am using a regular expression to read the values. Below is the code. Now, it reads...
21
by: Stephen.Schoenberger | last post by:
Hello, My C is a bit rusty (.NET programmer normally but need to do this in C) and I need to read in a text file that is setup as a table. The general form of the file is 00000000 USNIST00Z...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.