views:

293

answers:

4

I am trying to debug some homework but I am having trouble with these lines of code

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;

int main()
{
   char word;
   cout << "Enter a word and I will tell you whether it is" << endl <<
 "in the first or last half of the alphabet." << endl << 
   "Please begin the word with a lowercase letter. --> ";
   cin >> word;
   if(word[0] >= 'm')
     cout << word << " is in the first half of the alphabet" << endl;
   else
     cout << word << " is in the last half of the alphabet" << endl;
   return 0;
}  

I get the following error and I have no clue what its sayings

error C2109: subscript requires array or pointer type
A: 

word is declared as a char, not an array. But you're using word[0].

dcp
+2  A: 

The term subscript refers to the application of [] operator. In your word[0], the [0] part is a subscript.

The built-in [] operator can only be used with arrays or pointers. You are trying to use it with an object of type char (your word is declared as char), which is neither an array nor a pointer. This is what the compiler is telling you.

AndreyT
Ohhh, what throws me off is I was told that a char is an array of characters. So I thought I would be able to individualy access those characters regardless if I declared varible as an array or not.
numerical25
@numerical25: you really ought to read at least one good book on C and/or C++ programming, otherwise you're constantly going to be running into minor problems like this caused by a lack of basic knowledge of the language(s) in question.
Paul R
A: 

Instead of

char word;

declare

string word;

You already included the string-class header. Then you can access the elements with the []-operator.

Additional remark: Why do you use conio.h? It is obsolete and is not part of the C++ standard.

Lucas
Alternately, he could change the test to `if (word >= 'm')`; that is, lose the subscript.
John Bode
@John: I think he wants to output the whole word inside the if-statement and not just the first letter.
Lucas
+1  A: 

Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand.

int main(void)
{
    static const char prompt[] =
    "Enter a word and I will tell you whether it is\n"
    "in the first or last half of the alphabet.\n"
    "Please begin the word with a lowercase letter. --> ";

   string word;
   cout.write(prompt, sizeof(prompt) - sizeof('\0'));

   getline(cin, word);

   cout << word;
   cout << "is in the ";
   if(word[0] >= 'm')
     cout "first";
   else
     cout << "last";

   cout << " half of the alphabet\n";
   return 0;
}

For Your Information (FYI):

  1. stdafx.h is not a standard header and not required for small projects.
  2. conio.h is not a standard header and not required for simple console I/O.
  3. Prefer string for text rather than char *.
Thomas Matthews