C++ 在c++;以及将字符串存储在单独的变量中
我有一个类似这样的文本文件C++ 在c++;以及将字符串存储在单独的变量中,c++,parsing,vector,text-files,C++,Parsing,Vector,Text Files,我有一个类似这样的文本文件 lastname firstname, id 我想遍历文本文件,将每条记录添加到一个向量中,该向量包含3个变量:lastname、firstname、id 这是我正在使用的代码,但由于某些原因,我没有得到我想要的输出 int Student::readStudents(vector<Student> &term){ ifstream infile("spring2011.txt"); if ( !infile ) { cout
lastname firstname, id
我想遍历文本文件,将每条记录添加到一个向量中,该向量包含3个变量:lastname、firstname、id
这是我正在使用的代码,但由于某些原因,我没有得到我想要的输出
int Student::readStudents(vector<Student> &term){
ifstream infile("spring2011.txt");
if ( !infile ) {
cout << "Error attempting to open file ... "
<< "(Perhaps it dosen't exist yet?)" << endl;
return -1; // report error condition ...
}
term.clear(); // empty the student vector
string lname,fname, id;
int j;
while(infile){
getline( infile, lname, ' ');
getline(infile,fname, ',');
getline(infile, id, ' ');
term.push_back( Student(lname, fname, id) ); // construct and add new Student
j++;
}
infile.close();
return j; //count of records
}
int Student::readStudents(向量和术语){
ifstream-infle(“spring2011.txt”);
如果(!infle){
cout我猜,您实际上正在构造一个ifstream
对象,但没有打开文件对其执行输入操作。您缺少ifstream
对象构造的第二个参数,该参数实际上打开文件,就好像调用打开文件一样。因此,请尝试-
ifstream infile("spring2011.txt", ifstream::in );
或
将代码缩进四个空格。不要使用制表符。到底出了什么问题?向量中没有存储任何内容吗?或者是其他问题吗?向量中没有存储任何内容,我得到一个包含学生姓名的文本文件,如Bob Marley,011…我想浏览文本文件,将Bob添加到fname,Marly添加到lname,011添加到id…和pus在我想能够访问向量并打印它之后,它会这样打印:你应该尝试插入一些couts,这样我们就可以看到你实际读写的内容。我做了,这就是我的输出。1.姓名:Hofnar Tudor 002 Wright Matthew 003,学号:但我希望它看起来像:1.姓名:Hofnar都铎学生编号:002 2.姓名:Wright Matthew复制问题中文本文件spring2011.txt的内容。但它们位于彼此下方,即两个学生位于两个不同的位置lines@AngadSoni-这是不是一个打字错误,getline(infle,fname,“,”)
有,
作为delimeter。它不应该是空格字符吗?
ifstream infile("spring2011.txt", ifstream::in );
ifstream infile;
infile.open ("spring2011.txt", ifstream::in);