繁体   English   中英

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

[英]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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM