How would I get one character from this string?

I have a string ("ABC") and I want to retrieve the first letter from it. I then want to turn that single letter into a char. How would I do this? This is what I've tried so far:

1
2
3
4
5
6
7
8
9
10
11
double gpa(string letterGrades){
  double calculatedGPA = 0.0;
	for(int i = 0;i<letterGrades.length();i++){
	    string oneLetter = letterGrades.substr(i,i+1);
		oneLetter.c_str();
		calculatedGPA = gpa(oneLetter);
	}


	return calculatedGPA;
}


But this won't run...it gives me the error of "Unhandled exception at 0x7729dd7e in GPACalc2.exe: 0xC00000FD: Stack overflow."
With std::string you can just use operator [].
Try using this in the main function

1
2
string letters = "ABC";
char letterN = letters[0];
Thanks.

1
2
string letters = "ABC";
char letterN = letters[0];


worked perfectly.
You can also do this with an array of strings.
Here's one I made earlier...


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
#include <iostream>		// cout
#include <string>		// strings

bool vowel( std::string in[], const int &i, const int &j )
{
	if( ( in[ i ][ j ] == 'a' ) ||
		( in[ i ][ j ] == 'e' ) ||
		( in[ i ][ j ] == 'i' ) ||
		( in[ i ][ j ] == 'o' ) ||
		( in[ i ][ j ] == 'u' ) )
			return true;

	return false;
}

int main( int argc, const char *argv[] )
{
	std::string input[ 3 ];

	input[ 0 ] = "Hello";
	input[ 1 ] = "there";
	input[ 2 ] = "Lynx876.";

	for( int i = 0; i < 3; ++i )
		for( unsigned int j = 0; j < input[ i ].size(); ++j )
			if( vowel( input, i, j ) )
				std::cout << "Vowel: " << input[ i ][ j ] << ' ' << "In word " << i + 1 << ", Letter " << j + 1 << '\n';

	for( int i = 0; i < 3; ++i )
		std::cout << input[ i ] << ' ';

	std::cout << '\n';

	return 0;
}


EDIT:
i represents the word and j represents the letter.
Last edited on
use the [(unsigned int)] operator to retrieve the element from the string.

For example, string foo("This is a string"); // foo[0]= 'T
Topic archived. No new replies allowed.