简体   繁体   中英

Extract letters from a string and convert to upper case?

Here is a program in C++ for a string that accepts all characters but only outputs the letters; if letters are lower case then we should make them upper case.

#include<iostream>
#include<cstdlib>
#include<cctype>
#include <iomanip>
#include <cstring>

using std :: cin;
using std :: cout;
using std :: endl;
using std::setw ;

const int MAX_STR_LEN=100;

int main()
{
    char str1 [MAX_STR_LEN];
    int i;

    cin >> setw(MAX_STR_LEN) >> str1;

    for (int i=0; i <MAX_STR_LEN; i++) 
    {
        if (isalpha(str1[i])) {
            if (str1[i]>='A'&& str1[i]<= 'Z')
                cout << str1[i]; 
            if (str1[i]>='a'&& str1[i]<= 'z')
            {
                str1[i]= toupper(str1 [i]);
                cout << str1[i]; 
            }
        }
    }
    return EXIT_SUCCESS;
} 

This tends to work fine but gives extra letters, seems like I'm overlooking something. Also, when I only input numbers it gives letters such as PHUYXPU , something that I didn't input.

for (int i=0; i <MAX_STR_LEN; i++)

This would mean that you would iterate all the 100 cells of the array irrespective of the length of the string. You should either initialise the array before the cin statement like:

for(i=0;i<MAX_STR_LEN;i++)
str1[i] = '\0';

or replace the condition in the for loop to iterate only through the length of the array like:

for(int i=0;i<strlen(str1);i++) { 
//blah blah blah

In C++, you can do a lot without a raw loops, try this:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

struct to_upper {
    char operator()(char c) { return toupper((unsigned char)c); }
};

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

    string letters, input;
    cout << "Enter your name: ";
    getline(cin, input);

    copy_if(begin(input), end(input), back_inserter(letters), ::isalpha);
    transform(begin(letters), end(letters), begin(letters), to_upper());

    cout << letters << endl;
}

Result:

Enter your name: m1ar7ko0
MARKO

如果我做对了,则不需要isalpha()函数,那么您已经在删除数字和符号以及后续的if(str1 [i]> ='A'&& str1 [i] <='Z')和if(str1 [i]> ='a'&& str1 [i] <='z')。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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