二进制文件中的字符串,结构

String in binary files, struct?

本文关键字:结构 字符串 二进制文件      更新时间:2023-10-16
#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);