尝试执行时出现 cin.getline 错误

Having a cin.getline error while trying to execute

本文关键字:cin getline 错误 执行      更新时间:2023-10-16
每次

尝试运行此代码时,我都会收到错误。错误在我的 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 样式字符串。