从文件中读取两个向量

reading two vectors from file

本文关键字:两个 向量 文件 读取      更新时间:2023-10-16

问题在这里描述。我试图使用以下代码来解决它,但它不起作用。

const char* filename = "test.txt";
ifstream file1(filename);
vector<int> v1;
vector<int> v2;
vector<int> res;
int number;
char c;
while(1){
    while(1){
        v1.push_back(number);
        file1.get(c);
        if (c==';') break;
    }
    while(1){
        v2.push_back(number);
        file1.get(c);
        if (c=='n') break;
    }
    for (vector<int>::iterator it = v2.begin(); it!=v2.end(); it++)
        cout << *it << ',';
    cout << endl;
    file1.get(c);
    if (c==EOF) break;
    file1.unget();
}

阅读末端存在问题。c=='n'对吗?

要阅读一行,您应该使用:

istream& getline (istream& is, string& str, char delim);

在您的情况下,使用';'

的定界符

然后,您可以使用','

的定界符以相同的方式解析数字

这样:

std::string line, temp;
std::getline(file1,line,';'); //get a line. (till ';')
std::istringstream s1 (line); //init stream with the whole line
while(std::getline(s1,temp,',')){//get a number as string from the line. (till ',')
   int n;
   std::istringstream s2(temp);
   s2>>n; //convert string number to numeric value
   //now you can push it into the vector...
}