The useful way to think about this one is that you are doing a lookup, not a search through the sentence. You read the replacement pairs into two parallel arrays first, then walk the sentence one word at a time and ask of each word: is this on the list? If it is, print its partner instead. If it is not, print it unchanged.
Reading the input is straightforward because the format tells you the counts before it gives you the data, so you always know how many times to loop. That is what the leading 3 and the 15 are there for.
#include <iostream>
#include <string>
using namespace std;
int main() {
int numPairs;
cin >> numPairs;
string original[50];
string replacement[50];
for (int i = 0; i < numPairs; i++) {
cin >> original[i] >> replacement[i];
}
int numWords;
cin >> numWords;
for (int i = 0; i < numWords; i++) {
string word;
cin >> word;
for (int j = 0; j < numPairs; j++) {
if (word == original[j]) {
word = replacement[j];
break;
}
}
cout << word << " ";
}
cout << endl;
return 0;
}
A few things in there are worth pointing out.
Using two arrays that line up, so that original[j] and replacement[j] are always a matched pair, is the simplest way to store this. Reading both in the same cin line keeps them in step automatically.
The break matters. Once you find the match you are done with that word, and without the break the loop keeps comparing against the remaining pairs. The problem says the original words are unique, so there is never a second match to find, but breaking is the habit worth building.
Reading with cin >> word rather than getline is what makes this easy, because cin >> splits on whitespace for you, so each read hands you exactly one word already separated out. That is also why the word count is given.
I compiled and ran this against the sample. Given the three pairs and that fifteen word sentence, it prints: The car maker recommends car seats for kids if the car doesn't already have one.
Note that punctuation rides along attached to its word, so "one." stays "one." and "doesn't" is treated as a single word. That is fine here, but it is the thing that would break if a replacement word ever appeared with a comma stuck to it.