mid_code
mid_code

Reputation: 21

Strings and user input C++

I'm supposed to read an integer n from the user, which is the followed by n words, and then what follows after that is a sequence of words and punctuation terminated by the word END. For example:

2 foo d  
foo is just food without the d . END

The n words are to be "redacted" from the second line. So it would show up as:

*** is just food without the * . 

I think I can figure out the redacting part. I just cannot seem to figure out how to read the words in... any help is much appreciated!

#include <iostream>
#include <string>
using namespace std;

int main()
{
int n;
cin >> n;

string *redact = new string[n]
for(int i = 0; i < n; ++i)
    cin >> redact[i] // this part works!

return 0;
}

Upvotes: 0

Views: 338

Answers (1)

g-217
g-217

Reputation: 2210

Following code will cater the purpose.

#include <iostream>
#include <string>
#include <set>

int main()
{
  int n;
  std::cin >> n;

  std::set<std::string> redact;
  std::string word;
  for(int i = 0; i < n; ++i)
  {
    std::cin >> word;
    redact.insert(word);
  }
 while( std::cin>> word && word != "END" )
 { 
     if ( redact.find(word) == redact.end() )
        std::cout<<word<<' ';
 }
 std::cout<<'\n';
return 0;
}

I believe you are a learning C++, please note a point use typesafe, bound-safe and scope-safe C++.

So, no new delete unless you can call yourself an adept. Use the algorithms and containers provided by C++, instead of inventing your own.

Upvotes: 2

Related Questions