Question

I am trying to get read in some text about 100 char long or less and then strip it of spaces, digits, special char, etc.. I was thinking about ways to go about doing this but I think I must have forgotten most of what I know about cstrings and such. I was originally trying to just take in basic characters and copy them into a new string but 1. I couldn't figure out how to write it so my compiler doesn't hate me and 2. I'm pretty sure I don't want the new, stripped string to have blanks in it (I'm pretty sure my code so far would cause that to happen, if it even worked).

char * userText="";
char * justCharTxt;

cout << "Enter text: " << endl;
cin.getline(userText, STRING_SIZE);
for (int i = 0; i < strlen(userText); i++){
    if (((userText[i] >= 'a') && (userText[i] <= 'z')) ||
        ((userText[i] >= 'A') && (userText[i] <= 'Z')))
        *justCharTxt = userTxt[i];
}

Some guidance on this issue would be awesome. Thanks!

Was it helpful?

Solution 2

  1. you need to init your strings, i.e., reserve a buffer
  2. you need to increment the dest pointer.
#include <iostream>
using namespace std;
int main(){
int const STRING_SIZE=20;
char userText[STRING_SIZE*2]="";
char justCharTxt[STRING_SIZE]="";
char * txtPt = justCharTxt;
cout << "Enter text: " << endl;
cin.getline(userText, STRING_SIZE);
for (int i = 0; i < strlen(userText); i++){
    if (((userText[i] >= 'a') && (userText[i] <= 'z')) ||
        ((userText[i] >= 'A') && (userText[i] <= 'Z')))
        *(txtPt++)= userText[i];
}
cout << justCharTxt << endl;
return 0;
}
$ clang++ justit.cpp
$ ./a.out
Enter text:
ab123 a
aba

OTHER TIPS

Just use a std::string, no need to fiddle around with char arrays or pointers.

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

int main()
{
  std::string line;
  getline(std::cin, line);

  line.erase(
    std::remove_if(line.begin(), line.end(),
      [](char c) {return !isalpha(c, std::locale());}),
    line.end()
  );

  std::cout << line << '\n';
}

Your char arrays do not have enough memory, and they are const. char userText[STRING_SIZE];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top