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

时间:2014-12-01 01:24:55

标签: c++ string

每次尝试运行此代码时都会出现错误。错误就在我的while循环上方(第13行或第15行)它与我的cin.getline有关。

错误说明:

1>e:\projects (programming 1)\string\string\string.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;
}

1 个答案:

答案 0 :(得分: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风格字符串。