【问题标题】:Storing files in arrays and vectors将文件存储在数组和向量中
【发布时间】:2017-07-15 18:28:37
【问题描述】:

我一直在试图弄清楚如何将 txt 文件中的字符串和双精度数存储在数组和向量中,但我就是想不通。我做了很多研究,但没有找到可以向我解释的东西。基本上,我的任务是从包含用户名密码和这种格式的货币或积分等数字的文件中读取。 恩尼斯塔\n 我的密码0rd1$$4 \n 436.18 \n

Enis1 tAh \n 我的密码\n 76.2 \n

\ 不在 txt 文件中,但名称 pass 和 number 在不同的行中,而不是文本的同一行

....

对于我知道大小的文件,我可以使用数组,对于那些我不知道大小的文件,我可以使用向量。然后要求用户输入用户名和密码,如果匹配则让用户登录并允许他访问银行帐户或查看积分。
这是我的代码:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>


void mainMenu();

using namespace std;




 int main(){

 ifstream storeFromFile("student_info.txt");

 vector<string> Usernames;
 string getUsernames;
 while (!storeFromFile.eof()) {
    cin.ignore();
    getline(storeFromFile, getUsernames);




  }
for (int i=0; i<=Usernames.size(); i++) {

Usernames.push_back(getUsernames);
cout << Usernames[0];
 }
 mainMenu();


 return 0;
 }



 void mainMenu(){
 cout <<"\n[DA] to view all grades" <<endl;
 cout <<"[T] to view top x students" <<endl;
 cout <<"[P] to view one grade in particular" <<endl;
 cout <<"[E] to exit\n" <<endl;
 }

【问题讨论】:

  • 请在互联网上搜索“StackOverflow C++ 读取文件分离”。已经有很多类似的问题了。
  • 我知道如何从文件中读取,但我不明白如何将它们存储在数组和向量中,因此我可以在用户输入的情况下使用它们。
  • 数组和向量具有相同的存储元素语法:a[index] = value; 你应该研究你最喜欢的向量参考,或在互联网上搜索“c++ 向量示例”。

标签: c++ arrays database file vector


【解决方案1】:

您确实想使用classstruct 对每条记录进行建模。

为记录(文本行)中的每个“列”或字段定义一个包含一个成员的类。

重载提取运算符operator &gt;&gt;,让您的类从流中输入每个成员。

将这些类的容器声明为您的数据库,例如std::vector&lt;Record&gt; database;

将输入循环更改为:

Record r;
while (data_file >> r)
{
  database.push_back(r);
}

这是读取 CSV 文件的本质(即使您的文件使用逗号以外的其他分隔符)。

【讨论】:

  • 有没有办法在不使用结构或类的情况下做到这一点,因为我不允许使用它们。如果你能向我解释一下,我真的很感激,我正在尽我所能,但我就是不明白,所以如果你能引导我完成它,那就太棒了。非常感谢。
  • 是的,您可以使用“平行”向量或数组来实现。在您最喜欢的参考资料中研究它们。
【解决方案2】:

您可以使用 struct 并定义文档的结构。然后逐行阅读。此链接可能会有所帮助。 https://www.devarticles.com/c/a/Cplusplus/Serialize-Your-Class-into-Streams-in-C/

【讨论】:

    【解决方案3】:

    我得到了答案

    const int sizeLimit = 50;
    string firstName[sizeLimit], lastName[sizeLimit], passWord[sizeLimit];
    double accountBalance[sizeLimit];
    int count = 0;
    
    ifstream readFile("Accounts.txt");
    
    while (!readFile.eof())
    {
        readFile >> firstName[count];
        readFile >> lastName[count];
        readFile >> passWord[count];
        readFile >> accountBalance[count];
        count++;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 2013-03-03
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      相关资源
      最近更新 更多