Beginner level Strings Question

Hello,
I have this program here that counts the # of letters in a string.
I do not want to use gets(string) since it is from C. I have tried getline(cin,string) but can't get it to work. Any ideas?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	char string[ 1000 ];
    int c = 0; 
	int	count[ 26 ] = { 0 };

    cout << "Enter a string" << endl;
	gets( string );
	
    while ( string[ c ] != '\0' ) // Considering characters from 'a' to 'z' only 
    {
		if ( string[ c ] >= 'a' && string[ c ] <= 'z' ) 
			count[ string[ c ] - 'a' ]++;
		c++;
    }
	
	for ( int i = 0 ; i < 26 ; i++ )
    {
		if( count[ i ] != 0 )
			cout << static_cast< char >( i + 'a' ) << " occurs " << count[ i ] << " times" << endl;
    }
    return 0;
}
For getting string input from ther user you can use:

string s; // string object, not cstring
getline(cin,s); // std::getline not istream::getline

or cstring:

char cstring[1000];
cin.getline(cstring,999);
Thanks for the help Texan40
1
2
char cstring[1000];
cin.getline(cstring,1000);


getline knows enough not to go out of bounds with the null terminator.

Link: http://www.cplusplus.com/reference/iostream/istream/getline/
Last edited on
Topic archived. No new replies allowed.