简体   繁体   English

字符串和用户输入C ++

[英]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. 我应该从用户那里读取一个整数n ,后跟n个单词,然后是一个单词序列和标点符号,以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. 从第二行开始“删除” n个单词。 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;
}

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++. 我相信您正在学习C ++,请注意一点,使用typesafebound-safescope-safe C ++。

So, no new delete unless you can call yourself an adept . 因此,除非您可以称自己为adept否则不要进行new delete Use the algorithms and containers provided by C++, instead of inventing your own. 使用C ++提供的算法和容器,而不要发明自己的算法和容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM