-6

我有这段代码,基本上是我在尝试学习 c++,但我不明白为什么我不断收到这两个错误

错误:在“cInputChar”中请求成员“length”,它是非类类型“char [0]”

错误:从 'char*' 到 'char' 的无效转换

我认为这与我声明 char 变量的方式有关cInputChar。问题肯定与getChar功能有关。

我的代码如下:

int getInteger(int& nSeries);
char getChar(char& cSeriesDecision, int nSeries);

int main()
{
int nSeries = 0;
char cSeriesDecision = {0};

getInteger(nSeries);

getChar(cSeriesDecision, nSeries);

return 0;
}

//The function below attempts to get an integer variable without using the '>>'    operator.
int getInteger(int& nSeries)
{

//The code below converts the entry from a string to an integer value.

string sEntry;
stringstream ssEntryStream;

 while (true)
 {
  cout << "Please enter a valid series number: ";
   getline(cin, sEntry);
   stringstream ssEntryStream(sEntry);

   //This ensures that the input string can be converted to a number, and that the series number is between 1 and 3.
   if(ssEntryStream >> nSeries && nSeries < 4 && nSeries > 0)
   {
       break;
   }
   cout << "Invalid series number, please try again." << endl;
 }
 return nSeries;
 }

 //This function tries to get a char from the user without using the '>>' operator.
 char getChar(char& cSeriesDecision, int nSeries)
 {
 char cInputChar[0];

 while (true)
 {
   cout << "You entered series number " << nSeries << "/nIs this correct? y/n: ";
   cin.getline(cInputChar, 1);

   if (cInputChar.length() == 1)
   {
     cSeriesDecision = cInputChar;
     break;
   }
  cout << "/nPlease enter a valid decision./n";
}

return cSeriesDecision;
}
4

1 回答 1

2
 char cInputChar[0];

你真的需要一个大小数组0吗?0在 C++中不能有一个大小数组。这根本不合法。

你需要类似的东西:

#define MAX_SIZE 256

char cInputChar[MAX_SIZE];

最好简单地使用std::string而不是 c 样式的字符数组。


从评论中的讨论:

@Inafune:请拿起一本好书。您不会通过添加和删除语法来学习任何编程语言,只是为了编译代码。永远不要在不了解其背后的目的的情况下编写任何一行代码。

于 2013-01-09T15:22:54.317 回答