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.
MAX_STR_LEN? You forgot to check for the terminating'\0'character.std::string?isalphaandtoupperdon't takechars. They takeints that hold the values ofunsigned char(orEOF, but that's not possible here). Callisalpha((unsigned char) str1[i])instead. Plenty of systems makeisalpha(str1[i])do the same thing, but on some, ifstr1[i] < 0,isalpha(str1[i])can misbehave quite badly, for example by crashing your whole program.