C++ 函数不适用于我的两个变量

标签 c++ function

我的代码应该分别询问某人的名字和姓氏,但我的函数由于某种原因跳过了姓氏。我该如何解决这个问题?

#include <iostream>
using namespace std;

void read_name(char first[], char last[]);

void read_name(char first[], char last[])
{
    cout << "your name is " << first <<  last << endl;
}

int main()
{
    char firstt[15], lastt[15];
    read_name(firstt, lastt);
    cout << "enter first name" << endl;
    cin.get(firstt, 15, '\n');
    cout << "enter last name" << endl;
    cin.get(lastt, 15, '\n');

    read_name(firstt, lastt);
    return 0;
}

最佳答案

问题是成员函数 get 没有从流中提取换行符。所以 get 的下一个调用什么也读不到。添加函数忽略的调用。例如

cout << "enter first name" << endl;
cin.get(firstt, 15, '\n'); 
cout << "enter last name" << endl;
cin.ignore();
cin.get(lastt, 15, '\n');

同时删除 read_name 的第一个调用,因为它没有任何意义。

编辑:我想你忘了写

char first[15];
char last[15];

在您的代码示例中

关于C++ 函数不适用于我的两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594565/

相关文章:

Javascript 按名称绑定(bind)事件处理函数

c++ - 简化位设置算法尝试

c++ - For循环添加到一个变量

c++ - 是否可以在编译时检查 const 值是否已知?

python - 如何使用 lldb 调试 C++ pybind11 模块?

c - 如果我想捕获我在 fun1 的正式参数中传递的值,我该怎么做?

function - 没有参数的VHDL函数?

c++ - 通过引用捕获异常

php - 如何在数组中查找一个值并使用 PHP 数组函数将其删除?

python - 将带参数的函数传递给Python中的另一个函数?