将字符数组拆分为字母数字字符和非字母数字字符



我只是一名学生,我想了解c++中的这个数组。

如何显示在数组k到数组n上输入的所有字母数字字符以及阵列t上的所有非字母数字?

这就是我做的,我不知道下一个是什么

int main(int argc, char *argv[])
{ 
   char k[8], n[8], t[8];
   int ctr, nctr, tctr;
   for(ctr=0; ctr<8; ctr++){ 
     cout << "Input 1st Element ";
     cin >> k[ctr];  
     if (isalnum(k[ctr]))
#include <string.h>
#include <iostream>
using namespace std;
int main(void) {
        char k[8], n[8], t[8];
        strcpy(k,"--------");
        strcpy(n,"--------");
        strcpy(t,"--------");
    for (int pos = 0, tcntr = 0, ncntr =0; pos < 8; pos++) {
            cout<<"Input your char < : ";
            cin>>k[pos];
                if (isalnum(k[pos])) {
                        n[ncntr] = k[pos];
                        ncntr++;
                } else {
                        t[tcntr] = k[pos];
                        tcntr++;
                }
        }
        cout<<"Alpha numernic chars ::"<<n<<endl;
        cout<<"Non Aplha numberic chars ::"<<t<<endl;
}

Input your char < : 3
Input your char < : ^ 
Input your char < : d 
Input your char < : &
Input your char < : f
Input your char < : 1
Input your char < : 7
Input your char < : 1
Alpha numernic chars ::3df171--
Non Aplha numberic chars ::^&------

如何显示在数组k到数组n上输入的所有字母数字字符以及数组t上的所有非字母数字字符?

我想你说的"展示"是指"复制"吧?只需使用一个条件:

int ctr, nctr = 0, tctr = 0;   // note how I explicitly set the counters to 0
for (ctr = 0; ctr < 8; ctr++)
{ 
    cout << "Input Element " << ctr << ": ";
    cin >> k[ctr];  
    if (isalnum(k[ctr]))
    {
        n[nctr++] = k[ctr];
    }
    else
    {
        t[tctr++] = k[ctr];
    }
}

如果这不是你想要的,请提供更多信息。

如果允许使用STL,则partition_copy是最佳解决方案。您可以通过检查给定的谓词(在您的情况下,char是否为字母数字)将数组k拆分为两个数组nt。像这样:

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{ 
  const size_t len = 8;
  char k[len], n[len], t[len];
  // Input your data...
  // Copy all alphanumeric chars in n and non-alphanumeric to t
  partition_copy(k, k + len, n, t, isalnum);
}

最新更新