Question

Reading file with get().

Asked by: Marty21

Hi all,

I have a .txt-file with a random number (eg zipcodes, size is varying though) followed by a string (eg city name) on each line.
My intention is to read the file line per line and place the number in an int and the 'city name' in a string, to use both parameters in a constructor later on.
I'm not sure if I'm doing something wrong with the string pointer declaration or with the get()function..I was trying to have the number delimited by the space inbetween number and name on the file. I'm new at C++, programming altogether. Would anyone have any suggestion?


#include <iostream.h>
#include <fstream.h>

void main()
{
     ifstream in;
     ofstream out;

     char ch;
     char* zipcode;
     char* cityname;


     in.open("postcody.txt");
        while (!in.eof()) {
//          in.get(ch);
          in.get(zipcode, ' ');
          if (!in.eof())
          {
//               cout << ch;  
               out << cityname;
               in.close();

          }
     }

     in.close();
     cout << endl << "done" << endl;
}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-03-12 at 03:17:04ID20547615
Topic

C++ Programming Language

Participating Experts
6
Points
75
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. constructors
    What is the use of having a constructor in a private section.
  2. How to match duplicate cities in map?
    I have 2 input files a.txt & b.txt contents of a.txt are Auckland,1747564,-368536 Auckland,100000,-3556677 Christchurch,1726460,-435233 fields are city,x,y contents of b.txt are 1706,Auckland,Williams Avenue 1706,Auckland,Willow Way 1706,Auckland,Wyman Place fields are ...
  3. Classes and constructors: member initialization
    I'm working on this banking program (for school), and I was asking yesterday in another question about how constructors work and how to implement them into my program. So here is what I have so far: #include <iostream> #include <cstdlib> #include <string> ...
  4. Conversion Constructor
    I was trying to create this class...and I am required to create constructors using conversion constructor. Am I on the right path? I am getting the results, but ai m not sure if this is the reight way to do it? any suggestions... Thanks ======================= //classTime....
  5. Copy constructor or parameterized constructor
    Hi all, I am getting a strange compilaton error.... I am working on g++ 3.4.2..... Following is the scenario..... I have two independent classes(A and B) and a global function which returns reference to an instance of class A. class A{ public: A() { ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Marty21Posted on 2003-03-12 at 03:30:04ID: 8118599

Actually I forgot to mention that the reason I wrote this is also because when I run this program as is above, executing it let's the console crash for some reason...

I'll convert the zipcode-string later on in an int. Is this a preferred way to do it?


 

by: IvaandrPosted on 2003-03-12 at 03:50:42ID: 8118698

#include <iostream.h>
#include <fstream.h>

void main()
{
    ifstream in;
    ofstream out;

    char ch;
    char zipcode[6];  //NOTE, that length of zipcode must be equivalent vith length from file
    char cityname[255];  //try 255, if length of cityname not more, than 255


    in.open("postcody.txt");
       while (!in.eof()) {
         in.get(zipcode,6);
         in.get(cityname,255);
         cout<<"zip:"<<zipcode<<";city: "<<cityname<<endl;
        }
    in.close();
    cout << endl << "done" << endl;
}

 

by: madfacePosted on 2003-03-12 at 03:57:36ID: 8118715

insted of char* for zipcode and cityname try
char zipcode[20];

your pointers where not initizied so they are pointing in odd spots. Also i beleive get() will not allocate memory for you so you must use an array.

 

by: Marty21Posted on 2003-03-12 at 04:43:31ID: 8118880

Actually I forgot to mention that the reason I wrote this is also because when I run this program as is above, executing it let's the console crash for some reason...

I'll convert the zipcode-string later on in an int. Is this a preferred way to do it?


 

by: oferhPosted on 2003-03-12 at 04:50:57ID: 8118933

why dont you do:

in.open("postcody.txt");
      while (!in.eof()) {
         in >>zipcode >>cityname;
}
       

 

by: Marty21Posted on 2003-03-12 at 04:51:20ID: 8118937

(sorry for the earlier repeated comment, refreshing this page is not allowed it seems..)

So, using get(), I'm not able to let the program decide at runtime how many chars need to be read..? (in case of different zipcode sizes (US <-> European). That's why I was trying to figure out a way through pointers. I have tried to add
char* zipcode = NULL;

but that still gave the execute-crash..

 

by: Marty21Posted on 2003-03-12 at 05:06:48ID: 8119014

I tried that oferh,
it still crashes on me..
Doing that does that mean it automatically skips all whitespaces?

 

by: SaltePosted on 2003-03-12 at 07:44:07ID: 8120205

One minor point.

Not sure if it is smart to specify zip code as number. For US and possibly for most countries there are numeric codes for this kind of thing, but they often have letters or something around them. For example in Norway we use a 4 digit number as zip code but if sending from abroad we sometimes prefix that 4 digit number with "N-" indicating 'Norway' so a zipcode of 1234 would be N-1234. Such a zip code would crash if you require the zipcode to be a pure number.

I think the safest bet is to just treat the zipcode like a string just like the city name. It just often happen to be a number but that is irrelevant. If you want an integer for fast lookup, use a hash function from the zipcode string and use the integer value from that hashfunction as your integer value.

Alf

 

by: Marty21Posted on 2003-03-12 at 11:30:59ID: 8121855

It's more that I'm trying to challenge myself with goals I set forward for myself.
The idea was to arrange citynames using the postalcodes int value (in ascending order), eventually using balanced trees..I have a long way to go, but it kinda bothers me that I'm losing time trying to figure out why I get this error when I execute.

"reading.exe has encountered a problem and needs to close. We are sorry for the inconvenience. (with of course no further explanation really except some dump code)"

I was using postal codes coz I had a file already written in that format. But in the end I didn't want to restrict myself to just the 6 numbers of the USA...I wanted eventually to use a file that could have numbers from 1-1 million or so. That's why I was hoping using pointers would've helped me out. But according to this error message it won't let me.
You're right I was going to use the zipcode as string and then convert it to int. As for hashfunction, I have read something about hashtables but I haven't been quite into that. If I can't find no answer on the net here I guess I'll have to change my goals, like you said, but in my eyes it would be a shame not to learn why it didn't work :).

 

by: jadams117Posted on 2003-03-12 at 17:31:38ID: 8124342

I think the code below solves your problem. It's better to use the std::string class to hold strings if you don't know their length beforehand as it will be allocated dynamically as needed. Your crash was caused by the uninitialised char* pointers..

#include <fstream>
#include <iostream>
#include <string>
#include <conio.h>

int main()
{
     std::ifstream inFile("temp.txt");

     std::string zip;
     std::string city;

     while (!inFile.eof())
     {
          inFile >> zip >> city;
          std::cout << zip << ' ' << city << '\n';
     }

     while (!kbhit());
     return 0;
}

 

by: DarthNemesisPosted on 2003-03-12 at 17:42:37ID: 8124400

Do you have any objections to working with a string object? Character arrays are more efficient when your data is strictly organized, but it's a pain to try to allocate them correctly when you don't know how long they have to be.

BTW, your program was crashing becase you declared the variables as pointers but didn't allocate any memory for them, i.e. char* zipcode = new char[5].

Anyway, here's an example using strings that works fine:

#include <iostream.h>
#include <fstream.h>
#include <string.h>
using namespace std;

void main()
{
        ifstream in("postcody.txt");
        string zipcode, cityname;
        while (!in.eof()) {
                in >> zipcode >> cityname;
                // add storage operations here
                cout << zipcode << " " << cityname << endl;
        }

        in.close();
        cout << endl << "done" << endl;
}

And yes, the extraction operator >> ignores whitespace.

 

by: jadams117Posted on 2003-03-12 at 17:45:30ID: 8124415

By the way:

The std:: parts indicate that the names 'ifstream', 'string' and 'cout' lie within the std namespace. This namespace is a convention used within the standard c++ libraries to prevent name-clashes in case you have any other objects with those same names

The line 'while (!kbhit());' is just a way of waiting for a keyboard event so that the DOS window doesn't close before you've read what's on the screen

 

by: Marty21Posted on 2003-03-13 at 06:50:45ID: 8128174

Thanks for your replies, I'm glad there are people like you willing to help people like me..:)
I was still wondering..

suppose the cityname has whitespaces still in its name (before the end of the line, but that I still need, like eg "Los Angeles"), how do I avoid the ifstream in to consider Angeles as a zipcode?
I've been trying things like (among others)
in.get(cityname,255,'\n');
but that didn't work..any ideas still?


(Also, I feel like both DarthNemesis and jadams117 should get points because both of you really helped me, but I'm afraid I can only give one of you points right (is there any way around this?)..I'll just use the time-factor then..(sorry DarthNemesis..can I reward you later on?))

 

by: DarthNemesisPosted on 2003-03-13 at 12:43:24ID: 8131249

All you should have to do is change one of the >> operators to getline:

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

void main()
{
       ifstream in("postcody.txt");
       string zipcode, cityname;
       while (!in.eof()) {
               in >> zipcode;
            getline(in, cityname);
               // add storage operations here
               cout << zipcode << " " << cityname << endl;
       }

       in.close();
       cout << endl << "done" << endl;
}

As for giving me points too, thanks, you can just start a new problem with a title like "Points for DarthNemesis" and I'll respond to it.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...