Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    forums
Old 10-28-2004, 10:58 AM   #1 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
question needing an answer

when i import a file using the is/os command (i'm not sure which one), how do i read what's in the file? there is only one word per line in the file.

ps. my main goal is to import a file, and then find the palindromes in the file and cout them.
Androto is offline   Reply With Quote
Old 10-28-2004, 12:49 PM   #2 (permalink)
ender
Code Monkey
 
ender's Avatar
 
Join Date: Mar 2003
Location: Evansville, IN
Posts: 75
ender is on a distinguished road
Send a message via AIM to ender Send a message via Yahoo to ender
If you have access iostream (or the entire STL for that matter), it is a simple matter of using ifstream. Using ifstream, you can read in one word at a time and check to see if a word is a palidrome. The following would probably do it: (except check for palidromeness)

Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int isPalidrome (string aWord) {
   // Your code here
}

int main (int argc, char * argv[]) {
    ifstream inFile ("path/to/file.txt");
    string aWord;
    int numPalidromes = 0;
    
    if (!inFile.is_open()) {
        cout << "Error opening file!\n";
        return -1;
    }

    inFile >> aWord;
    while (!inFile.eof()) {
        if (isPalidrome(aWord))
            numPalidromes++;

        inFile >> aWord;
    }

    cout << numPalidromes << endl;

    return 0;
}
Since C/C++ considers any whitespace to be a delimiter, it wouldn't matter if you had one word per line, or 100 words per line, as long as they are separated by some whitespace. When you say inFile >> aWord, it is the same thing as cin >> aWord, except that it is retrieving it from a file instead of stdin. Getting an entire line is a bit trickier, but since you don't need to do that, I won't cover it here.

The fstream class is the abstraction later on top of the OS to allow you to read and write from files. C++ is nice in this respect.

If you are not using C++, and instead are using straight C, the matter is a bit more difficult. Again, the same principle applies for whitespace, except it is a different set of functions to get data from the file. Furthermore, you have to work with char * instead of strings. The following should work (again, checking for palidromes is an exercise for the reader).

Code:
#include <stdio.h>

#define MAX_LEN 256

int isPalidrome (char * aWord) {
    /* Your code here */
}

int main (int argc, char * argv[]) {
    FILE * fileHandle;
    char word[MAX_LEN];
    int numPalidromes = 0;
    
    fileHandle = fopen ("/path/to/file", "r");
    if (!fileHandle) {
        printf ("Error opening file!\n");
        return -1;
    }

    fscanf(fileHandle, "%s", word);
    while (!feof(fileHandle)) {
        if (isPalidrome(word)) numPalidromes++;
        fscanf(fileHandle, "%s", word);
    }

    fclose (fileHandle);
    
    printf ("%d\n", numPalidromes);

    return 0;
}
That should do it for C. To open files and such in C you use the stdio routines located in stdio.h. It is a much more 'low level' way of doing things, but does work.

This code has been tested to compile on linux (gcc 3.3.3).

Good luck!
-Ted
__________________
while(1) fork();
ender is offline   Reply With Quote
Old 10-28-2004, 01:23 PM   #3 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Read this short thread. Read my comments on what is posted and learn:
Text program

Besides:
Quote:
Getting an entire line is a bit trickier, but since you don't need to do that, ...
You can't know in this stage. If you want to do some serious file checking (like format checking, integrity etc) one may use std::getline() instead.

The code below is just bad.
Quote:
inFile >> aWord;
while (!inFile.eof()) {
if (isPalidrome(aWord))
numPalidromes++;

inFile >> aWord;
}
Quote:
int isPalidrome (string aWord) {
// Your code here
}
bool isPalidrome(const string& aWord){...}

Basically this is the code:
Code:
   ifstream inFile ("path/to/file.txt");
   if (!inFile)
   {
      cout << "Error opening file!\n";
      return -1;
   }

   string theWord;
   while (inFile >> theWord)
   {
      if ( /* check_for_palidrome_with_theWord() */ )
      {
         cout<<theWord<<endl;
      }
   }

   //If file-reading loop exits before EOF has been reached, something is wrong.
   if( !inFile.eof() )
   {
      cout<<"ERROR: Something went wrong during processing of file."<<endl;
   }
__________________

Last edited by Valmont; 10-28-2004 at 01:54 PM.
Valmont is offline   Reply With Quote
Old 10-28-2004, 04:27 PM   #4 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
thx for you're help, i'll give it a try, if i have anymore questions regarding this i'll just ask.
Androto is offline   Reply With Quote
Old 10-29-2004, 04:09 PM   #5 (permalink)
gamehead200
Code Monkey
 
gamehead200's Avatar
 
Join Date: Oct 2004
Posts: 57
gamehead200 is an unknown quantity at this point
Valmont, I'm doing the same thing as Andrew, except a different way... What am I doing wrong??

Code:
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    int i = 0;
    string word, wordreverse;
    unsigned size;
    
    ifstream in_file("c://Temp//scrabble.txt");  // open a file at this location
	
    while( !in_file.eof() ) 
    {        
        while( in_file >> word )
        {
            size = word.size();  // count number of letters in the word
            
            while( i < size )  // while i is less than size, reverse the word
            {
                wordreverse += word[size-i-1];
                i++;  // increment i
            }
            
            if( word == wordreverse )  // compare the two words
            {
                cout << word << " is a palindrome." << endl;  // if palindrome
            }
            
        }    
        
    }   
       
    system("PAUSE");	
    return 0;
}
gamehead200 is offline   Reply With Quote
Old 10-29-2004, 06:47 PM   #6 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
The main() follows below. But first read this link:
Text program
Note what I have to say about file i/o handling. Next time I want to see that back in your code :).

Also, you know what wait_for_enter() is by now.

Code:
int main(int argc, char *argv[])
{
   string word, wordreverse;
   ifstream in_file("c:/Temp/scrabble.txt");  // open a file at this location
   if( !in_file )
   {
      cout<<"Opening file failed."<<endl;
      wait_for_enter();
      return 1;
   }
   
   unsigned size;
   while( in_file >> word )
   {
      size = word.size();  // count number of letters in the word
      while( size > 0)
      {
         wordreverse += word[size-1];
         --size;
      }
      // compare the two words
      if( word == wordreverse )
      {
         cout << word << " is a palindrome." << endl;
      }
      //Reset the reversed word for new iteration.
      wordreverse="";
   }
   
   if( !in_file.eof() )
   {
      cout<<"Something went wrong during processing of file."<<endl;
      wait_for_enter();
      return 1;
   }
   
   //Line below: optional right now. in_file destructor will close it anyway.
   //in_file.close()

   wait_for_enter();
   return 0;
}
__________________
Valmont is offline   Reply With Quote
Old 10-29-2004, 07:24 PM   #7 (permalink)
gamehead200
Code Monkey
 
gamehead200's Avatar
 
Join Date: Oct 2004
Posts: 57
gamehead200 is an unknown quantity at this point
Valmont, I understand what you mean when you say not to use the while( !in_file.eof() ) loop, however, why do you use the while( in_file >> word ) instead? Doesn't this just read the word from the file in a loop?
gamehead200 is offline   Reply With Quote
Old 10-29-2004, 07:50 PM   #8 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
Quote:
Originally Posted by gamehead200
Valmont, I understand what you mean when you say not to use the while( !in_file.eof() ) loop, however, why do you use the while( in_file >> word ) instead? Doesn't this just read the word from the file in a loop?
this means: while (in_file is still being read).....





that's the best wording i can put it in. i'm sure valmont can explain it better
Androto is offline   Reply With Quote
Old 10-29-2004, 07:52 PM   #9 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
question, this should work right? i only got one error while compiling so i really couldn't test it. can someone please run it and explain to me what i did wrong?
Code:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

using namespace std;
void wait_for_enter();
void palindrome(string line);
string reverse(string line);
string verify(string reversed);


int main()
{
    string line;
    ifstream scrabble("/Users/andrewassaly/Desktop/scrabble_words.txt");
    if (!scrabble.is_open())
    {
        cout << "Error, cannot find file" << endl;
        wait_for_enter();
        return 13;
    }
    while (!scrabble.eof())
    {
        scrabble >> line;
        palindrome(line);
    }    
    wait_for_enter();	
    return 0;
}
///////////////// Palindrome /////////////////////
void palindrome(string line)
{
    string reversed;
    reversed = reverse(line);
    verify(reversed);
    wait_for_enter();
}    
///////////////// reverse///////////////////////
string reverse(string wordin)
{
    string wordr;
    int i, j;
    i = 0;
    j = wordin.size() -1; // -1 because an array starts counting at 0, not 1
    wordr = wordin;
    /* this while loop reverses the wordin
    it does this by taking the letter at i and making it equal to the letter
    at j*/  
    while (j >= 0)
    {
        wordr[i] = wordin[j];
        i++;
        j--;
    }
    return wordr;
/////////////////////verify ///////////////////////
void verify(string reversed, string wordin)
{
    if (reversed == wordin)
    {
        cout << wordin << " is a palindrome!!!!" << endl << endl;
    }
    else
    {
        cout << wordin << " is not a palindrome!!!" << endl << endl;        
    }
}
///// i need this code for mac, other system paus does not work/////
void wait_for_enter()
{
  cout << "press <enter> to continue...";
  cin.clear();
  string line;
  getline( cin, line);
}
Androto is offline   Reply With Quote
Old 10-29-2004, 08:21 PM   #10 (permalink)
gamehead200
Code Monkey
 
gamehead200's Avatar
 
Join Date: Oct 2004
Posts: 57
gamehead200 is an unknown quantity at this point
You're missing a } after return wordr;

:p
gamehead200 is offline   Reply With Quote
Old 10-29-2004, 08:57 PM   #11 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Quote:
Originally Posted by gamehead200
You're missing a } after return wordr;

:p
Androto, you are still using faulty code.
__________________
Valmont is offline   Reply With Quote
Old 10-29-2004, 08:58 PM   #12 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Quote:
Originally Posted by gamehead200
Valmont, I understand what you mean when you say not to use the while( !in_file.eof() ) loop, however, why do you use the while( in_file >> word ) instead? Doesn't this just read the word from the file in a loop?
No, because at each read, an internal pointer is moved up with one. So the next time the next item is read if exists.
Eacht time a valid item is read, a value that can be interpreted as "true" returns to the while statement.
__________________
Valmont is offline   Reply With Quote
Old 10-29-2004, 09:15 PM   #13 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Quote:
Originally Posted by Androto
ifstream scrabble("/Users/andrewassaly/Desktop/scrabble_words.txt");
if (!scrabble.is_open())
{
cout << "Error, cannot find file" << endl;
wait_for_enter();
return 13;
}
The code above is wrong. That means, the cout<<"Error:.." is wrong. You can't know why the file didn't open correctly. Perhaps it's there but something else is wrong. So change your output to something more general.
Code:
    while (!scrabble.eof())
    {
 }
No.
Code:
while(infile>>myString) { }
Dot it right.

Code:
///////////////// Palindrome /////////////////////
void palindrome(string line)
{
    string reversed;
    reversed = reverse(line);
    verify(reversed);
    wait_for_enter();
}
The wait_for_enter() doesn't belong there. It belongs in verify(). But that's wrong too. I told you to let it return a bool only. Don't let it do two things. Let it only verify. Learn it the right way while you can.

Code:
///////////////// reverse///////////////////////
string reverse(string wordin)
{
    string wordr;
    int i, j;
    i = 0;
    j = wordin.size() -1; // -1 because an array starts counting at 0, not 1
    wordr = wordin;
    /* this while loop reverses the wordin
    it does this by taking the letter at i and making it equal to the letter
    at j*/  
    while (j >= 0)
    {
        wordr[i] = wordin[j];
        i++;
        j--;
    }
    return wordr;
You forgot a }.
Besides, don't use c-style comments, e.g. /* */ when coding C++.

Code:
/////////////////////verify ///////////////////////
void verify(string reversed, string wordin)
{
    if (reversed == wordin)
    {
        cout << wordin << " is a palindrome!!!!" << endl << endl;
    }
    else
    {
        cout << wordin << " is not a palindrome!!!" << endl << endl;        
    }
}
The cout doesnt belong there. Functions do one distinguished thing only!
Make it so:
bool verify(string reversed, string wordin)
If your functions do more things then expected then the effect of functions is gone. A function groups code for a single purpose task. Image all the functions in a bigger program do multiple things. What a mess is that going to be.

Quote:
///// i need this code for mac, other system paus does not work/////
void wait_for_enter()
{
cout << "press <enter> to continue...";
cin.clear();
string line;
getline( cin, line);
}
Mac or no mac, this is the way to go.
__________________
Valmont is offline   Reply With Quote
Old 10-30-2004, 09:53 AM   #14 (permalink)
gamehead200
Code Monkey
 
gamehead200's Avatar
 
Join Date: Oct 2004
Posts: 57
gamehead200 is an unknown quantity at this point
Quote:
Originally Posted by Valmont
No, because at each read, an internal pointer is moved up with one. So the next time the next item is read if exists.
Eacht time a valid item is read, a value that can be interpreted as "true" returns to the while statement.
OK, makes a bit more sense now... Still a bit confused, but not as much as before... I'll probably understand it in a bit...

Thanks again, Valmont!

(BTW, the forums are having cookie problems... I get logged out whenever I close the window... Never had this problem before... )
gamehead200 is offline   Reply With Quote
Old 10-30-2004, 01:33 PM   #15 (permalink)
Androto
Mac Os X User(I hate win)
 
Join Date: Oct 2004
Posts: 138
Androto is on a distinguished road
Quote:
Originally Posted by gamehead200
(BTW, the forums are having cookie problems... I get logged out whenever I close the window... Never had this problem before... )
same here
Androto is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Quick question on <table>'s Redline HTML, XML, Javascript, AJAX 3 10-30-2004 09:12 PM
Compiler Question cheawick Standard C, C++ 3 04-30-2004 04:06 AM
Database Design Question sde Program Design and Methods 7 04-25-2003 06:55 PM
Easier answer? Kernel_Killer HTML, XML, Javascript, AJAX 4 02-26-2003 01:13 PM
Question about a php prediction script(Great Site!) Geetazz PHP 15 06-12-2002 06:37 PM


All times are GMT -8. The time now is 07:16 AM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.0.0 RC8





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting