avoiding overwrite with user input?

another i'm sure easy question.
here, as an exercise, i made a simple case-reverser and i'm trying to figure out how to impose limits on user input so no overwrite of adjacent memory occurs. as it is, the loop catches any input length <1 or >10 but the overwrite still occurs if the user enters a too-long string at first. i just chose 10 as an arbitrary string length to experiment with and the for loop on line 23 was just a diagnostic thingy for me to verify that the overwrite was in fact occurring.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdio>

using namespace std;

void invertCASE(char *st);

int main (){
    int ct; char ans[10];
    do{cout<<"\nEnter a character string: ";gets(ans);}
    while (strlen(ans)<1||strlen(ans)>10);
    invertCASE (ans);
    cout<<"\n\n\nModified string: ";
    for (ct=0;ans[ct];ct++) cout<<ans[ct];
    cout<<"\n\n\n";
}

void invertCASE (char *st){
           int ct; char *ts=st;
           cout<<"\n\n";
           for (ct=0;ct<30;ct++) {cout<<*st;st++;} cout<<"\n\n";
           for (ct=0;*ts;ct++) {
               if (isupper(*ts)) {*ts=tolower(*ts);}
                else if (islower(*ts)) {*ts=toupper(*ts);}
               ts++;}
               }
       


thanks!

ps- thanks for help with pointers yesterday, i think i'm starting to get it now
Last edited on
Please, learn how to properly format code. Your program won't get any faster from squishing as much information as possible into a single line.
Why not use a string variable instead of a char[].
It worries me that you specify a length to the char array, without knowing how many characters the user might input. Although, the compiler might still compile it, and as you say, store the chars in adjacent memory locations. I would use the string class.
Topic archived. No new replies allowed.