尝试执行时出现 cin.getline 错误
Having a cin.getline error while trying to execute
每次
尝试运行此代码时,我都会收到错误。错误在我的 while 循环(第 13 或 15 行)正上方,这与我的cin.getline
有关。
错误指出:
1>e:projects (programming 1)stringstringstring.cpp(15) : error C2664:
'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>
::getline(_Elem *,std::streamsize)' : cannot convert parameter 1 from 'char' to 'char *'
是的,我尝试使用cin >> ans;
,这给了我一个运行时错误。
谢谢你,如果你花时间帮忙! :D
// Zachary Law Strings.cpp
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
int main()
{
char ans;
cout << "Would you like to work with the string program? Please type 'y' or 'Y' to execute the program: ";
cin.getline(ans, 2);
while (ans == 'Y' || ans == 'y')
{
int x, i, y;
char name[] = "Please enter your name: ";
char answer1[80];
string mystring, fname, lname;
i = 0;
y = 0;
cout << name;
cin.getline(answer1, 79);
cout << endl;
x = strlen(answer1);
for (int i = 0; i < x; i++)
{
cout << answer1[i] << endl;
if (isspace(answer1[i]))
{
y = i;
}
}
cout << endl << endl;
cout << setw(80) << answer1;
mystring = answer1;
fname = mystring.substr(0, y);
lname = mystring.substr(y, x);
cout << "First name: " << fname << endl;
cout << "Last name: " << lname << endl;
mystring = lname + ',' + fname;
cout << setw(80) << mystring;
cout << "Would you like to work with the string program again? Please type 'y' or 'Y' to execute the program: ";
cin >> ans;
}
return 0;
}
std::istream::getline()
函数需要一个char*
参数,该参数意味着一定大小的缓冲区。
至少对于您读取单个字符的情况,您可以提供一个缓冲区,例如
char ans[2];
cin.getline(ans, 1); // << You only want to read a single character
并将循环条件更改为
while (ans[0] == 'Y' || ans[0] == 'y') {
// ...
}
std::istream::getline()
应该将结果写入char[]
缓冲区,从而生成终止零的 C 样式字符串。
相关文章:
- 而循环跳过 cin.getline() 对于 C 字符串
- 重用字符数组和 cin.getline
- 如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒
- 必须使用 cin.getline() 按回车键两次
- 填充字符数组的最佳方法(获取与cin.getline)
- 递归 cin.getline() 不想要求输入
- 如何阻止 cin.getline() 导致控制台在找不到分隔符时重复获取用户输入?
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- cin.getline() 不适用于 switch 语句
- C++ 在 switch 语句中,cin.getline 不会分配给 c 字符串变量
- cin.getline() 等待输入
- 为什么cin.getline分配给字符数组,但使用'='不会?
- cin.getline(),而不使用字符串大小
- cin.getline 不使用 switch 语句
- cin.getline()函数在CIN之后无法正常工作
- Cin.Getline(char,int)在循环中被跳过
- C++ cin.getline 只读取一个字符
- CIN / Getline在控制台应用程序中的一行中
- cin.getline()的奇怪行为
- cin.getline()未按预期工作