hi guys just a query basically I have created the following program, which takes a word then shows the position of a certain character. Now what I need to do is then print out each characters position in the array: so for example
T E S T
0 1 2 3.. etc

I just need some help on how to implement this into my code, I'm assuming it would be by storing the values then using pointers??

Many Thanks

#include <string>
#include <iostream> // allows program to output data to the screen
#include <cstring>
using std::string;
using std::strlen;
using std::cout; // program uses ‘cout’
using std::cin; // program uses ‘cin’
using std::endl; // program uses ‘endl’
int main()
{
string s1;
int location;
int locationL;
const int MAXINPUT = 128;
char inputBuffer[MAXINPUT];
const int FIRSTINPUT = 128;
char findFirst[FIRSTINPUT];
cout << "Please input a string: " <<endl;
cin.getline(inputBuffer,MAXINPUT);
 
//void getLength()
{
cout << "You input: " <<endl;
cout << inputBuffer <<endl;
cout << "The length of the string is: " << strlen(inputBuffer) <<endl;
string str1( inputBuffer );
cout << "Please enter a character to search for: ";
cin >> s1;
 
int location = str1.find(s1);
cout << "First occurrence of '" << s1 << "' at: " << location+1 << endl;
int locationL = str1.find_last_not_of(s1);
cout << "Last occurrence of '" << s1 << "' at: " << locationL+2 << endl;
cout << "Reverse string: ";
for(int i = str1.length()-1; i >= 0; i--)
{
cout << str1 [i] ;
} cout << endl;
return 0;
}
}

Recommended Answers

All 3 Replies

use a loop starting at index zero going to length of string. In body of loop output current char and index using whatever format you want.

can you use cout with memory addresses though? I thought that printf may have to be used?

char array[] = inputBuffer;
cout << &char array[0] << endl;

would something like that work, although would'nt it print the whole string.

>>char array[] = inputBuffer;

That won't work but this will:

char array[] = "inputBuffer";

Reason, string literals need to be enclosed by double quotes. My snippet is called initialization of the string.

>> cout << &char array[0] << endl;

That should print out the address of the element of array whose index is zero, or the address of the first element of array. This should print out the first element of array:

cout << array[0];

and this should print out all of array, one element at a time.

int len = strlen(array);
for(int i = 0; i < len; ++i)
cout << array;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.