return a specific character from a string?

Hi,

I'm looking for a function call that will return a specific character from a string. I need to create a program that will ask the user for a word, ask for a number, then the program will display a character from the string that matches with the number.

So say a user enters the word flamingo, 4, then the program shows the letter i.

This is what I have so far:

=======================================================================
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
#include "pch.h"
#include "iostream"
#include <string>
using namespace std;

int main()
{
	string city;
	int charNum, charResult;

	cout << "Input your favorite city: ";
		cin >> city;
	cout << "Which character you would like to display: ";
		cin >> charNum;

		charResult = ;

	cout << "The user entered: " << city << endl;
	cout << "The character at position " << charNum << " is: " << charResult << "\n\n"; 



		system("pause");
	return 0;
}

=======================================================================

Trying to put the function in charResult.
It's been about a year since I last programmed, so I'm stuck.

Thanks!
Last edited on
> I'm looking for a function call that will return a specific character from a string

See: https://en.cppreference.com/w/cpp/string/basic_string/operator_at
Make sure that the position entered by the user is a valid position within the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    std::string word ;
    std::cout << "enter a word: " ;
    std::cin >> word ;

    std::size_t pos ;
    std::cout << "enter the position of a character (a number, zero is the first position): " ;
    std::cin >> pos ;

    std::cout << "you entered " << std::quoted(word) << '\n' ;

    if( pos < word.size() )
        std::cout << "the character at position " << pos << " is '" << word[pos] << "'\n" ;

    else std::cout << "invalid position " << pos << '\n' ;
}
Thank you so much, I really appreciate it! I knew it was simple but I couldn't find it in my notes or online.
Topic archived. No new replies allowed.