二进制文件中的字符串,结构
String in binary files, struct?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct client {
public:
char name[10];
int balance;
char id[5];
};
int main()
{
int ans;
int x;
string nameIn;
string adjName;
ofstream out("client1.dat", ios::binary);
cout << "nDo you want to add information or update info" << endl;
cin >> ans;
if (ans == 1)
{
cout << "nPlease enter the name of your client" << endl;
cin >> nameIn;
while (nameIn.length() <=10)
{
for (int i=0; i < 10; i++)
{
adjName[i] = nameIn[i];
}
}
while (10-adjName.length()>0)
{
int x = 10 - adjName.length();
for (x; x< 10; x++)
{
adjName[x] = ' ';
}
}
for (int i = 0; i < adjName.length(); i++)
{
client name = adjName[i];
}
但是这部分一直显示为错误
for (int i = 0; i < adjName.length(); i++)
{
client name = adjName[i];
我试图让用户写一个名字,如果它超过 10 个字母,它会切断它,或者更短它会添加空格。另外,有人可以解释为什么您不能将字符串写入二进制文件吗?如果我使用字符串,为什么我必须使用结构而不是类。
首先,你的代码中有一个错别字:client name = adjName[i];
没有意义。你忘了那个点吗?
其次(也是最重要的(您在C++代码中使用 C 字符指针。除非你不得不这样做,否则你不应该这样做——现在没有必要。您的代码应如下所示:
struct client {
std::string name;
};
// read the data
name = nameIn.substr(0, 10);
相关文章:
- C++结构到字符串
- 从字符串中获取结构的大小
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何解析表示树状数据结构的字符串
- 如何将字符串与结构(也包括字符串)进行比较?
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 将字符串存储在 constexpr 结构中
- 为什么我的结构在包含字符串时崩溃?
- 如何将字符串字符与结构数组进行比较?
- 无法使用 strcpy 将字符串复制到静态结构成员
- c++ 将函数参数(带有模板变量的结构)转换为函数体内的字符串
- 在 c++ 中使用字符串变量选择静态类结构,而不带对象
- 如何输出属于向量数组的结构字符串
- 为什么我不能像正常一样初始化 typedef 结构字符串或字符?
- 如何引用结构字符串成员
- c++运算符+=重载结构字符串
- 如何将平面列表合并转换为层次结构字符串
- 如何在c++中比较两个结构字符串