我的代码应该分别询问某人的名字和姓氏,但我的函数由于某种原因跳过了姓氏。我该如何解决这个问题?
#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/