gpt4 book ai didi

c++ - 在结构中使用 getline 获取 char 类型名称

转载 作者:行者123 更新时间:2023-11-28 06:10:31 24 4
gpt4 key购买 nike

正如我声明的结构数组:struct name data[5];当我尝试使用 cin.getline(data[i].full_name,75) (我需要)获取输入时,它会在第一次后跳过 char 输入。我在这个网站上搜索并使用了 fgets 但没有用。 代码是:

#include<iostream>
using namespace std;

struct name
{
char full_name[75];
int number;
};

void input(struct name data[])
{
int i=0;
while(i<5)
{
cout<<"Enter the name: ";
fgets(data[i].full_name,75,stdin);
OR
cin.getline(data[i].full_name,75)


cout<<"Enter the number: ";
cin>>data[i].number;
i++;
}
}

int main()
{
int times=0;
struct name data[5];
input(data);
}

最佳答案

以下是我的建议,希望对您有所帮助:

void input(struct name data[])
{
int i=0;
int number;
char asciNumber[75];
while(i<5)
{
cout<<"Enter the name: ";
cin.getline(data[i].full_name,75);
cout<<"Enter the number: ";
cin.getline(asciNumber,75);
try
{
number = atoi(asciNumber);
data[i].number = number;
}
catch (...)
{
//cout << "error in number parsing" << endl;
// i think its important to check validity of std input\
}
i++;
}
}

关于c++ - 在结构中使用 getline 获取 char 类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com