向量问题,也许有点手

Vector problems, a little hand maybe?

本文关键字:也许 问题 向量      更新时间:2023-10-16

我正在尝试创建一个程序,该程序读取文本文件中的内容,然后在向量中的两个元素之间交换位置。

文本文件具有以下顺序:名称,姓氏,注册,_number和city_adress。

清单约100人。我想知道是否有一种方法不包括整行并将其结束在空间中。

这是我的代码的样子!

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
  vector<string> line;
  string information;
  ifstream myfile ("Namn.txt");
  if (myfile.is_open()) {
    while (getline(myfile, information)) {
      line.push_back (information);
    }
    myfile.close();
  }else cout << "Filen gick inte att öppna!";
  for (unsigned int i = 0;  i < line.size(); i++) {
    cout << line[i] << endl;
  }
  return 0;
}

您可以使用fstream读取文件并同时解析您的文件,然后将信息的所有元素放在向量的向量中,然后您可以混合并匹配您喜欢的信息位,这样:

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
int main()
{
    std::string name;
    std::string surname;
    std::string registration;
    std::string location;
    std::vector<std::vector<std::string>> information;
    std::ifstream myfile("Namn.txt");
    while (myfile >> name >> surname >> registration >> location)
        information.push_back({name, surname, registration, location});
    // print
    for (auto const &info : information)
    {
        std::cout << info[1] << " " << info[0] << " " << info[2] << " " << info[3] << std::endl;
    }
    return 0;
}

打印:

Andersson Rune 12873645 Stockholm
Isaksson Peter 12873645 Uppsala
Gustavsson Fredrik 12873645 Gothenborg