why won't this assign a string to ch?

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
30
31
32
33
34
35
36
37
38
/*
    chCase Version2
*/

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
  char ch[11];
  int i;
  while(true)
  {
    cout << "Please enter a letter (no more than ten, enter \".\" to exit): ";
    gets(ch);
    for(i = 0; ch[i]; i++)
    {
      //detect for a period
      if(ch[i] == '.')
      {
        cout << ch;
        break;
      }
      //detect for any error
      else if(!isalpha(ch[i])) continue;
      //change case
      else 
      {
        islower(ch[i])?toupper(ch[i]):tolower(ch[i]);
        if(i == 9) cout << "the new letters are: " << ch << "\n";
      }
    }
    if(ch[i] == '.') break;
  }
  return 0;
}

im assuming it has something to do with one of these 2 lines:
char ch[11];

or
gets(ch);

because when i run it, it doesnt print anything except "Please enter a letter (no more than ten, enter "." to exit): ".
Could you be a bit more specific? What's happening when you enter text? Or does the program just end?
Your code will only print something if the word is 9 characters long. if(i == 9) cout << "the new letters are: " << ch << "\n";<--- This is why.
Try this instead. if(i == strlen(ch) - 1) cout << "the new letters are: " << ch << "\n"; or put cout << "the new letters are: " << ch << "\n"; before the return 0;. I personally avoid strlen(ch) for checking cstring length most of the time, because it relies on the '\0' character being present at the end of the string but in this case i guess it'll suffice.

Also if you're running this from an IDE which closes the console once the main returns put a cin.get() before the return 0; as well.
Last edited on
Topic archived. No new replies allowed.