gpt4 book ai didi

c++ - 为什么我不能在下面的代码中输入空格?

转载 作者:行者123 更新时间:2023-11-28 05:46:42 28 4
gpt4 key购买 nike

请看下面的代码。如果我为变量名提供“空格”输入,另一个整数变量不会存储在文件中。为什么?我也发布了输出。

    #include<iostream>
#include<fstream>
#include<cstring>
using namespace std;

int main()
{
int age;
char name[100];

ofstream obj,obj10;
obj.open("lol.dat", ios::trunc);
cout<<"Enter Name"<<endl;

cin.getline(name,100);
cin.ignore();
obj<<name<<endl;
cout<<"Enter age"<<endl;

cin>>age;
cin.ignore();
obj10<<age<<endl;
obj.close();
//read

ifstream obj2;
obj2.open("lol.dat");
obj2>>name;
cout<<"Name:"<<name<<endl;
obj2>>age;
cout<<"Age:"<<age<<endl;
obj2.close();
return 0;
}

我的输出:

 Enter Name
Ankith

Enter age
1234
Name:Ankith
Age:1234

Enter Name
Ankith Prabhas

Enter age
12345
Name:Ankith
Age:0

我需要做什么才能将全名“Ankith Prabhas”作为一个输入和另一个整数?

最佳答案

尝试在您希望有空格的字符串中使用 getline()。

关于c++ - 为什么我不能在下面的代码中输入空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076705/

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