Please help me with this C++ assignment! RIGHTMOST CHAR CHALLENGE DESCRIPTION: Y
ID: 3834321 • Letter: P
Question
Please help me with this C++ assignment!
RIGHTMOST CHAR
CHALLENGE DESCRIPTION:
You are given a string 'S' and a character 't'. Print out the position of the rightmost occurrence of 't' (case matters) in 'S' or -1 if there is none. The position to be printed out is zero based.
INPUT SAMPLE:
The first argument will be a path to a filename (e.g. the program was executed with >>> ./a.out input.txt <<<<< ), containing a string and a character, comma delimited, one per line. Ignore all empty lines in the input file. E.g.
OUTPUT SAMPLE:
Print out the zero based position of the character 't' in string 'S', one per line. Do NOT print out empty lines between your output.
E.g.
Explanation / Answer
PROGRAM CODE:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int rightMostChar(string word, char ch)
{
for(int i=word.length()-1; i>=0; i--)
{
if(word[i] == ch)
return i;
}
return -1;
}
int main(int argc, char *argv[]) {
string line = "";
// from the question it is understood that the file name will be provided as a command line argument. So this is where we instantiate the file stream
ifstream in(argv[0]);
// This is where we read through each line of the file
while(getline(in, line))
{
string word1, word2;
char ch;
stringstream ss(line);
// here we are reading each word of the file after splitting them with the delimitter as ','
getline(ss, word1, ',');
getline(ss, word2, ',');
cout<<rightMostChar( word1, word2.at(0))<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.