C++ ifstream,加载时出现问题,";"

C++ ifstream, issue loading with ";"

本文关键字:问题 ifstream 加载 C++      更新时间:2023-10-16
int a, b;
while (infile >> a >> b)
{
    // process pair (a,b)
}

所以这是我一直在看的代码,但我遇到了一个问题,因为我的字符串之间没有空格,它们有";">
我的代码:

void load(string filename){ // [LOAD]
    string line;
    ifstream myfile(filename);
    string thename;
    string thenumber;
    if (myfile.is_open())
    {
        while (myfile >> thename >> thenumber)
        {
        cout << thename << thenumber << endl;
        //map_name.insert(make_pair(thename,thenumber));
        }
        myfile.close();
    }
   else cout << "Unable to open file";
}

[Inside the txt.file]
123;peter
789;oskar
456;jon

我现在得到的是"thename"为123;peter和"thenumber"为789;oskar。我希望"thename"作为peter,"thenumber"作为123,这样我就可以正确地将其插入到我的地图中,如何?

infile>> 从 for a 的合格类型文件中读取。在你的例子中,a 是 int,所以">>"期望找到一个 int。在您的代码中,myfile>>名称>>数字都是字符串类型,因此它们期望文件中的字符串类型。问题是字符串包含";",因此变量名称将占用所有行,直到找到(换行符(。

在您的代码中

std::string thename, thenumber; char delimeter(';'); //It is always '-' is it? std::getline(std::cin, thename, delimeter); std::getline(std::cin, thenumber);

数字也将是字符串类型。要将数字转换为 int:

std::istringstream ss(thenumber);
int i;
ss >> i;
if (ss.fail())
{
    // Error
}
else
{
    std::cout << "The integer value is: " << i;
}
return 0;

这种格式读取文件相当简单。 您可以将std::getline与不同的分隔符一起使用,以告知它在哪里停止读取输入。

while(getline(myfile, thenumber, ';')) // reads until ';' or end of file
{
    getline(myfile, thename); // reads until newline or end of file
    map_name.insert(make_pair(thename,thenumber));
}

您必须输入一个字符串,然后将其拆分以获取名称和数字

....
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}
....
void load(string filename){ 
..........

    if (myfile.is_open())
    {
        while (myfile >>whole)
        {
             std::vector<std::string> parts = split(whole, ';');
             name = parts[0];
             number = parts[1];
        }
    }