Thread: File I/O Question

  1. #1
    Registered User
    Join Date
    Oct 2005

    File I/O Question

    Hey guys, the following code is part of a program I am working on and as a newbie to c++ I have come across a problem. As you can see when the case is J the int J is increased by 1 but how do I go about doing this if for example instead of J I want to use a word like joke? Is it possible using IF statements?

    Thanks in advance for any help.

    ifstream file("c:\file.txt");
        if (file.is_open())
        while (! file.eof() )
            while (file.get(ch))
    		switch (ch) {
                                 case 'j':

  2. #2
    Registered User
    Join Date
    Jan 2005
    A word like "joke" is a string, so to do this with a word instead of a character you must read in a string. Use the string datatype, and read in the word with file >> or getline. Use >> if you want only a single word, use getline if you want the whole line including spaces.

    Then you would need to use an if statement instead of a switch, since switch only works with integral types like int or char.

    BTW, you would want to put the call to operator>> or getline into the control of your while loop instead of eof(). That is not the best way to loop through the contents of a file because the read itself might fail. The return value of the operator>> call or the getline call automatically tells you if the read succeeded or failed, and so it will catch the end of the file automatically.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. File i/o and ASCII question
    By muzihc in forum C Programming
    Replies: 13
    Last Post: 11-04-2008, 11:46 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. File I/O Question
    By Achy in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 12:09 AM
  5. Another dumb question about file i/o
    By Cobras2 in forum C++ Programming
    Replies: 23
    Last Post: 03-14-2002, 04:15 PM