Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从文件中读取两个向量_C++_File - Fatal编程技术网

C++ 从文件中读取两个向量

C++ 从文件中读取两个向量,c++,file,C++,File,我试着用下面的代码来解决它,但它不起作用 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);

我试着用下面的代码来解决它,但它不起作用

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();
}
const char*filename=“test.txt”;
ifstreamfile1(文件名);
向量v1;
矢量v2;
向量res;
整数;
字符c;
而(1){
而(1){
v1.推回(数字);
文件1.get(c);
如果(c==';')中断;
}
而(1){
v2.推回(数字);
文件1.get(c);
如果(c=='\n')中断;
}
for(vector::iterator it=v2.begin();it!=v2.end();it++)

cout要阅读一行,你应该使用:

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...
}

c=='\n'应该匹配行尾字符。我认为您的问题在其他地方。可能有人会指出这一点,但您是否尝试过使用调试器?请在此处描述您试图执行的操作(不要链接到其他地方),并具体说明哪些操作不起作用(与问题有些无关),但您应该使用
while(c!=';)
while(c!='\n')
而不是
while(1)
。这被认为是更好的做法您重复存储同一个未初始化的数字。为什么您认为这是可行的?