Thread: Parsing text files.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Registered User
    Join Date
    Dec 2009
    Location
    /dev/pts/0
    Posts
    29
    Doing my best to understand what you mean . . .

    In other words, you are creating a list of names, let's say, "names.txt", that contains something much like:
    Code:
    Allen
    Brian
    Crystal
    David
    Ellen
    If someone enters the name "Brian", then your program will print "The name 'Brian' is in the list of names." -- whereas, if they enter "Varun", then the program will print "The name 'Varun' is not in the list of names."?

    If so, then you will need to use ifstream. One example of a program that reads in words, then prints them out to the screen on their own lines could be:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cstdlib>
    
    int main(int argc, char *argv[]) {
        if(argc != 2) {
            std::cout << "usage: " << argv[0] << " filename" << std::endl;
            exit(1); /* NOTE: I'm not sure, in C++, if exit() is actually std::exit() or not. Probably. */
        }
        std::ifstream file(argv[1]);
        if(!file.is_open()) exit(1);
        bool done = false;
        do {
            std::string word;
            file >> word;
            std::cout << word << std::endl;
            if(file.eof()) done = true;
        } while(!done);
        file.close();
        return 0;
    }
    In C++, it is possible to compare strings against each other (string1 == string2), since operator==(const std::string &) is implemented by default.

    That should be enough to get you started, at least.
    Last edited by strange; 12-10-2009 at 12:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help creating multiple text files
    By Tom Bombadil in forum C Programming
    Replies: 19
    Last Post: 03-28-2009, 11:21 AM
  2. Replies: 5
    Last Post: 02-11-2008, 01:36 AM
  3. Parsing Text File and gathering input variables
    By azamsharp1 in forum C Programming
    Replies: 2
    Last Post: 10-26-2005, 08:43 AM
  4. pointers into largish text files
    By donkeypunch in forum C++ Programming
    Replies: 8
    Last Post: 06-30-2004, 03:04 PM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM