Thread: string input from files

  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
    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, 02:20 PM
  2. Replies: 6
    Last Post: 01-03-2007, 03: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, 03:40 AM
  4. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM