string input from files

This is a discussion on string input from files within the C++ Programming forums, part of the General Programming Boards category; I need to read from a file, line by line, the text has blanks in it, I need to know ...

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    7

    how do I input strings from a file

    I need to read from a file, line by line, the text has blanks in it, I need to know the number of characters per line(included the blanks). I tried using getline, get, so that i could store a line in a string to work on it, but get and getline dont work with an ifstream variable, or at least i dont know how to do it.
    Last edited by jriano; 06-01-2003 at 01:25 PM.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    148
    getline works with file streams.
    Code:
    #include <string>
    #include <fstream>
    ....
    std::string input;
    ifstream file("data.txt");
    getline(file,input);

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    4

  4. #4
    RoD
    RoD is offline
    Redundantly Redundant RoD's Avatar
    Join Date
    Sep 2002
    Location
    Missouri
    Posts
    6,331
    OUTPUT:

    Characters on line one: 3
    Press any key to continue

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
    	char input;
    	int count = 0;
    
    	ifstream	infile;
    
    	infile.open("c:\\test.txt"); //premade text file
    
    	if (infile.fail())
    	{
    		cout << "Error loading file!" << endl;
    	}
    
    	infile >> input;
    
    	while (! infile.fail())
    	{
    		if (input != '\n')
    		{
    			count++;
    			infile >> input;
    		}
    		
    	}
    	
    	cout << "Characters on line one: " << count << endl;
    
    	return 0;
    }
    Attached is my text file i used, just paste it on your c drive.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 01:20 PM
  2. Replies: 6
    Last Post: 01-03-2007, 02:02 PM
  3. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 02:40 AM
  4. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 11:47 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21