How to count characters, but not spaces?

This is a discussion on How to count characters, but not spaces? within the C++ Programming forums, part of the General Programming Boards category; Hello, I am trying to figure out how I can count characters in a line, but not include the spaces ...

  1. #1
    Registered User
    Join Date
    Jan 2004
    Posts
    49

    How to count characters, but not spaces?

    Hello,

    I am trying to figure out how I can count characters in a line, but not include the spaces in this count. I realize that cin won't see "whitespace", but it isn't being very kind to me. I first tried cin.get(), but rather than going through the while loop, it just read the first line, then stopped. So far using the code I have, I can count the characters with the spaces included of each line, and display the line number, the line text itself and how many characters were in that line. Now if I could just get rid of those pesky spaces!
    Oh yes, one other troubling feature of my code is an annoying C4267 warning concerning the variable i. That variable is being set equal to line.size(). When I give "i" type size_t, then I get: C4267: 'argument' : conversion from 'size_t' to 'unsigned int', possible loss of datang. When I assign "i" as an unsigned int, then the warning remains the same. I am not sure what to do in this case. Any ideas?
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cassert>
    using namespace std;
    
    int charCount = 0;
    int main()
    {
    	string fileName;
    	cout << "Enter name of file: ";
    	getline(cin, fileName);
    
    	ifstream inFile(fileName.data() );
    	assert(inFile.is_open());
    
    	unsigned lineCount = 0;
    	unsigned i = 0;
        string line;
    
    	while (!inFile.eof())
    	{		
            getline(inFile, line);
            lineCount++;
    		cout << "\nline #" << lineCount;		
    		cout << " " << line << "\n";
    	    i = line.size();
    			cout << i << " characters in this line\n\n";
    				
          }
        inFile.close(); 
    	return 0;
    }
    Thank you for your time.
    Semper Fi!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    The easiest way would be to use get:
    Code:
    #include <cctype>
    ...
    while ( inFile.get ( c ) ) {
      cout<< c;
      if ( c == '\n' )
        linecount++;
      else if ( !isspace ( c ) )
        charcount++;
    }
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Hi prelude, you've helped me before. Thanks a bunch. I will see what that does for me. Any idea of what to do about that conversion warning?
    Semper Fi!

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Any idea of what to do about that conversion warning?
    The problem is here:

    >i = line.size();
    i is an unsigned int, but std::string's size member function returns string::size_type, which on your implementation is size_t. Declare i as
    Code:
    string::size_type i;
    And the warning will go away because your types will match.
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Whoah, that compounded 'me eager little problems. Now every where that "i" is used, I get a warning. (I have added some statements to calculate the line with the shortest and longest amount of characters, and to find the average)
    Semper Fi!

  6. #6
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    I haven't figured out a way to use your code that doesn't count the spaces. When I put it in my program, it printed out a running total for the characters, rather than a subtotal of characters for each line.
    Semper Fi!

  7. #7
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    Quote Originally Posted by RedZippo
    I haven't figured out a way to use your code that doesn't count the spaces. When I put it in my program, it printed out a running total for the characters, rather than a subtotal of characters for each line.
    Then just reset the charCount after every '\n' to get characters for individual line
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  8. #8
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Quote Originally Posted by alphaoide
    Then just reset the charCount after every '\n' to get characters for individual line
    I am not sure I know how to do that. I thought not counting the spaces was my biggest problem but it turns out I have far worse problems. I still have not been able to clear that conversion warning with the variable i. Also, I thought it would be straight-forward to figure out which line had the fewest amount of characters. Figuring out which has the most works just fine, and even finding the average was no problem. But when I look for
    Code:
     i = line.size();
    
                if (i > longest)
    		longest = i;
                if (i < shortest) 
    		shortest = i;
    shortest is always zero because of course "i" is never going to be less than shortest, it would have to be negative to be that. So I am stuck trying to figure out an algorythm to convince this heap of silicon and plastic to do what I want it to do, not just what I tell it to do.
    Here is the full code:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cassert>
    #include <cstdlib>
    using namespace std;
    
    
    int charCount = 0;
    int    longest,
           shortest,
    	   runner,
    	   average;
    
    
    int main()
    {
    
    
    
    	string fileName;
    	cout << "Enter name of file: ";
    	getline(cin, fileName);
    
    	ifstream inFile(fileName.data() );
    	assert(inFile.is_open());
    
    	unsigned lineCount = 0;
    	int i;
    	string::size_type i;  //if I use this then every instance of i produces a warning
        string line;
    	
    
    	while (!inFile.eof())
    	{		
            getline(inFile, line);
            lineCount++;
    		cout << "\nline #" << lineCount;		
    		cout << " " << line << "\n";
    		
    		
    		    i = line.size();
    
                if (i > longest)
    				longest = i;
                if (i < shortest) 
    				shortest = i;
    			runner += i;
    
                cout << "Shortest = " << shortest << "\n";  //remove after debugging
                cout << "The longest line is: " << longest << "\n";
    			cout << i << " characters in this line\n\n";			
    			
          }
                cout << "The shortest line is: " << shortest << "\n"; 
    			cout << "The longest line is: " << longest << "\n";
                average = runner / lineCount;
                cout << "The average is: " << average << "\n";
    	return 0;
    }
    Semper Fi!

  9. #9
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Hrm, well you forgot to get rid of the integer i...
    Code:
    unsigned lineCount = 0;
    	int i; //<-----
    	string::size_type i;  //if I use this then every instance of i produces a warning
        string line;
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  10. #10
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    >> I still have not been able to clear that conversion warning with the variable i.
    I don't get warning on VC++ 6.0

    Here is your code with *some* fixes to your problem. You just need to implement Prelude's code ('cause yours counts the spaces) and you're good to go.
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <cassert>
    #include <cstdlib>
    using namespace std;
    
    
    int charCount = 0;
    int longest,
         shortest,
         runner,
         average;
    
    
    int main()
    {
    
    	string fileName;
    	cout << "Enter name of file: ";
    	getline(cin, fileName);
    
    	ifstream inFile(fileName.data() );
    	assert(inFile.is_open());
    
    	unsigned lineCount = 0;
    
    	string::size_type i;  
            string line;
    	
            getline(inFile, line);
            i = line.size();
            shortest = i;
            longest = i;
    
    	while (!inFile.eof())
    	{		
                 if (i > longest)
    		  longest = i;
                 if (i < shortest) 
    		  shortest = i;
    		
                 runner += i;
                 lineCount++;
    	     cout << "\nline #" << lineCount;		
    	     cout << " " << line << "\n";
    		
    	     cout << i << " characters in this line\n\n";
          
                 getline(inFile, line);
                 i = line.size();			
            }
      
            average = runner / lineCount;
    
            cout << "The shortest line is: " << shortest << "\n"; 
    	cout << "The longest line is: " << longest << "\n";
            cout << "The average is: " << average << "\n";
    
    	return 0;
    }
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  11. #11
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,804
    You already seem to have an answer on how to count characters without counting spaces but here is one more way:
    Code:
    #include <algorithm>
    #include <functional>
    #include <string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        string line("This is a test sentence.");
        int count;
    
        count = count_if(line.begin(),line.end(),bind2nd(not_equal_to<char>(),' '));
    
        cout << "Length of string: " << line.length() << endl;
        cout << "Length minus ' ': " << count << endl;
    
        return 0;
    }
    Which outputs:
    Code:
    Length of string: 24
    Length minus ' ': 20
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  12. #12
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    [QUOTE=alphaoide]>> I still have not been able to clear that conversion warning with the variable i.
    I don't get warning on VC++ 6.0

    Here is your code with *some* fixes to your problem. You just need to implement Prelude's code ('cause yours counts the spaces) and you're good to go.

    I compiled this code and received 7 conversion warnings and one signed/unsigned mismatch warning. When I ran the code anyway, it runs in an infinite loop. I am using Microsoft Visual Studio.net
    However, atleast "shortest" now has the correct value. So what I need to do is find a compromise between my code, and the code you "fixed". Obviously an infinite loop is not very attractive.

    I still have no idea how to implement Preludes code. I don't know that much about C++.
    Semper Fi!

  13. #13
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    I don't get an infinite loop even in .NET. Make sure you copy everything correctly, better yet figure why it loops infinitely.

    About conversion warning do this one instead
    Code:
    int    i;
    .......
    i = static_cast<int>( line.size() );
    Explanation: line.size() returns a size_t, but then it's converted to an int, and the converted return values is stored to an int-type variable. No more mismatch!
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  14. #14
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Quote Originally Posted by alphaoide
    I don't get an infinite loop even in .NET. Make sure you copy everything correctly, better yet figure why it loops infinitely.

    About conversion warning do this one instead
    Code:
    int    i;
    .......
    i = static_cast<int>( line.size() );
    Explanation: line.size() returns a size_t, but then it's converted to an int, and the converted return values is stored to an int-type variable. No more mismatch!
    I apologize alphaoide, the cause of the infinite loop was of my own doing. Now I have a clean compile too! I can see the light at the end of the tunnel. Now I just have to figure out how to implement that wonderful code Prelude cooked up. Thanks for your help boss.

    "There are three kinds of people: Those who can count, and those who cannot."
    -unknown-
    Semper Fi!

  15. #15
    Registered User
    Join Date
    Jan 2004
    Posts
    49
    Quote Originally Posted by alphaoide
    Then just reset the charCount after every '\n' to get characters for individual line
    Can you give me some direction on how to reset charCount after every '\n'? I'd like to be able to solve this on my own, but I don't have a clue how to do this. It is probably something simple and I am just not "seeing" it after being so flustered with the other problems.
    Semper Fi!

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do you check how many characters a user has entered?
    By engstudent363 in forum C Programming
    Replies: 5
    Last Post: 04-08-2008, 06:05 AM
  2. consecutive number
    By stewie1986 in forum C Programming
    Replies: 3
    Last Post: 12-03-2007, 02:53 PM
  3. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM
  4. ascii characters video displaying on tv screen
    By deian in forum C Programming
    Replies: 6
    Last Post: 10-12-2004, 09:46 PM
  5. Characters in a txt file.
    By tay_highfield in forum C Programming
    Replies: 3
    Last Post: 01-31-2003, 08:19 AM

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