请给点指导
Some guidance please
我有这个代码,这基本上是我试图学习c++,我不知道为什么我一直得到两个错误
错误:请求成员'length'在'cInputChar'中,它是非类类型'char [0]'
和
错误:从'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;
}
char cInputChar[0];
你真的需要一个大小为0
的数组吗?在c++中不能有大小为0
的数组。这是不合法的。
你需要这样写:
#define MAX_SIZE 256
char cInputChar[MAX_SIZE];
最好使用std::string
而不是c风格的字符数组。
摘自评论中的讨论:
@Inafune:请挑选一本好书。通过添加和删除语法来编译代码是学不到任何编程语言的。如果不理解代码背后的目的,永远不要写任何一行代码。
相关文章:
- 没有找到相关文章