string subscript is out of range

Alright guys you can see what needs to be done for my assignment in the comment. When i run the program it crashes and tells me "string subscript is out of range.". If I ignore the error it runs and gives me the number of characters in the string like it should. Do I somehow have to give a max size to the string that is imputed?

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
29
30
31
32
33
34
35
36
37
38
39
/*
Write a function that returns an integer and accepts a pointer to a C- string as an argu-ment. 
The function should count the number of characters in the string and return that number. 
Demonstrate the function in a simple program that asks the user to input a string, passes it 
to the function, and then displays the functions return value.
*/

#include<iostream>
#include<string>

using namespace std;

int stringCount(string);

int main()
{
	string string;

	cout << "Enter string:" << endl;
	cin >> string;

	int strCount;
	strCount = stringCount(string);
	
	cout << "The number of characters in the string " << string << " is " << strCount << ".\n";

return 0;

}
int stringCount(string str)
{
	int count = 0;

	for(count; str[count] != 0; count++)
	{
	
	}
	return count;
}
You're attempting to use a std::string as though it was a c-string.
I believe you are supposed to be using a plain character array for this assignment.

The instructions read:
Write a function that returns an integer and accepts a pointer to a C- string as an argument.


so the function header should look like this:
int stringCount(char * str)

Also, instead of this:
1
2
3
	string string;
	cout << "Enter string:" << endl;
	cin >> string;

you should have something more like this:
1
2
3
	char string[100];
	cout << "Enter string:" << endl;
	cin >> string;

(or use cin.getline)
http://www.cplusplus.com/reference/istream/istream/getline/
Last edited on
Topic archived. No new replies allowed.