#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
usingnamespace std;
int main ()
{
std::cout << "Give a person a name: " << endl;
//string inputString;
string inputString;
cin >> inputString;
std::string s(inputString);
std::vector<char> myVector( s.begin(), s.end() );
for ( char c : myVector )
{
std::cout << c << endl;
}
for (int i = 0; i < myVector.size(); i++)
{
std::cout << i << "\n";
}
std::cout << "Enter the index of the letter you want to change: " << endl;
int index;
cin >> index;
if (index > myVector.size())
{
std::cout << "index is outside the vector" << endl;
}
else
{
std::cout << "Enter the characters index: " << endl;
char newChar;
std::cout << "Type in a letter to be replaced with another: ";
cin >> newChar;
for (unsignedint i = 0; i < myVector.size(); i++)
{
if (myVector[i] == index)
{
myVector[i] = newChar;
std::cout << myVector[i] << " ";
}
}
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
usingnamespace std;
int main()
{
std::cout << "Give a person a name: " << endl;
//string inputString;
string inputString;
cin >> inputString;
std::string s( inputString );
std::vector<char> myVector( s.begin(), s.end() );
for( int i = 0; i < myVector.size(); i++ )
{
std::cout << i << " - " << myVector[i] << "\n";
}
std::cout << "Enter the index of the letter you want to change: " << endl;
int index;
cin >> index;
if( index > myVector.size() )
{
std::cout << "index is outside the vector" << endl;
}
else
{
char newChar;
std::cout << "Type in a letter to be replaced with another: ";
cin >> newChar;
myVector[index] = newChar;
}
for( int i = 0; i < myVector.size(); i++ )
{
std::cout << i << " - " << myVector[i] << "\n";
}
return 0;
}
Give a person a name:
angstrom
0 - a
1 - n
2 - g
3 - s
4 - t
5 - r
6 - o
7 - m
Enter the index of the letter you want to change:
4
Type in a letter to be replaced with another: h
0 - a
1 - n
2 - g
3 - s
4 - h
5 - r
6 - o
7 - m
@patriic48 - Your if statement inside your last for loop is wrong. What you are doing there is checking if element at index i is equal to index (comparing char to int) that is why your program exits and you never assign new char. Also even though you are iterating through the entire vector to find if i == index, your cout will only print the element at index i and not the entire vector with new char at selected index.
You can modify your for loop to look like this:
1 2 3 4 5 6 7 8 9
for(int i = 0; i < myVector.size(); i++)
{
if(i == index) //instead of myVector[i] == index
{
myVector[i] = newChar;
}
std::cout << myVector[i] << " ": //moved from if block
}