Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 错误C2109:下标需要数组或指针类型_C++_Visual Studio 2008 - Fatal编程技术网

C++ 错误C2109:下标需要数组或指针类型

C++ 错误C2109:下标需要数组或指针类型,c++,visual-studio-2008,C++,Visual Studio 2008,我正在试着调试一些家庭作业,但是我在这些代码行上遇到了问题 #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

我正在试着调试一些家庭作业,但是我在这些代码行上遇到了问题

#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;
}  
word被声明为字符,而不是数组。但是您使用的是单词[0]。

术语下标指的是[]运算符的应用。在您的单词[0]中,[0]部分是一个下标

内置[]运算符只能与数组或指针一起使用。您正试图将其用于char类型的对象,您的单词被声明为char,它既不是数组也不是指针。这是编译器告诉您的。

而不是

char word;
申报

string word;
您已经包含了字符串类标题。然后可以使用[]-运算符访问元素


附加说明:为什么使用conio.h?它是过时的,不是C++标准的一部分。

< P>另一个建议:声明输出文本为一个实体,然后块写入。这可能使您的程序更易于调试、阅读和理解

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;
}
供您参考:

stdafx.h不是标准标头 小型项目不需要。 conio.h不是标准的收割台 简单控制台不需要 输入输出。 文本首选字符串,而不是 字符*。
哦,让我不舒服的是我被告知一个字符是一个字符数组。所以我认为我可以单独访问这些字符,不管我是否声明变量为数组。@数字25:你确实应该读至少一本关于C和/或C++编程的好书,否则,你会经常遇到这样的小问题,这是由于缺乏相关语言的基本知识造成的;也就是说,丢失下标。@John:我想他想在if语句中输出整个单词,而不仅仅是第一个字母。
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;
}