打印不在c ++行中的字母

时间:2015-10-29 18:27:33

标签: c++

所以,我要做的是,打开并读取一个文件,但只读第一行。我已经完成了这一部分。我必须阅读该行上的每个字符,然后我需要打印在该行中找不到的字母。

让我们说这条线是: a b c D E f G H I j k L M n o

所以,我必须打印p-z中的字母,因为它们不在行中。

那么,如何获得不在行中的字母?!

这是我到目前为止所做的:

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

int main(int argc, char *argv[]){

  if(argc < 2){
    cerr << "Usage: pangram <filename>" << endl;
    return 0;
  }

  ifstream infile(argv[1]);
  if (infile.good() == false){
    cerr << "Error opening file[" << argv[1] << "]" << endl;
    return 1;
  }

  char ch;
  string line;
  int a[26] = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z};
  int brk = 0;

  while(infile.good()){
    if(brk == 0) {
      getline(infile, line);
      for(int i=0; i <= line[i]; i++){
        if(isalpha(line[i])) {
          if(line[i] == )
          cout << line[i] << endl;
        }

      }
    }
    brk ++;

    if(brk == 1) {
      break;
    }
  }
}

2 个答案:

答案 0 :(得分:0)

Here's a slightly modified version of your solution. I'm intentionally using a stack allocation of 26 bools instead of bitset so it's easier to comprehend. bool letter_was_seen[26] = {}; // initialize an array to hold 26 bools (A..Z) all to false getline(infile, line); // read a line into a string size_t len = line.size(); for (size_t i = 0; i < len; i++) { char ch = ::toupper(line[i]); // convert to upper case if ((line[i] >= 'A') && (line[i] <= 'Z')) // is it a valid letter A..Z ? { letter_was_seen[ch - 'A'] = true; // mark it's place in the array as "seen" } } // now print the letters not seen within the line for (char i = 'A'; i <= 'Z'; i++) { int index = (int)(i - 'A'); if (letter_was_seen[index] == false) { cout << i; // print the letter not seen } } cout << endl; // print end of line to flush output

答案 1 :(得分:0)

另一种可能的解决方案,

#include <deque>
#include <algorithm>
#include <iostream>

using namespace std;

int main() {
  deque<char> allChars(26);
  iota(allChars.begin(), allChars.end(), 'a');

  char readString[] = "test xyz";

  for (char& c : readString) {
    allChars.erase(remove(allChars.begin(), allChars.end(), c),
                   allChars.end());
  }

  cout<<"Not removed: ";
  for (char& c : allChars) {
    cout<<c<<" ";
  }
  cout<<endl;
}