我编写了一个完整的程序,其中包含您上面提到的所有内容读取单个元素的字符缓冲区,然后将它们复制到对。我还确保我不会在文件末尾做一些疯狂的事情,以防没有读取两个元素(无论文件末尾是否有 \n,它都有效)。
#include <fstream>
#include <iostream>
#include <list>
#define BUF 100
using namespace std;
int main() {
std::ifstream myReadFile;
std::list<std::pair<std::string,std::string> > startTape;
std::pair<std::string,std::string> pair;
char sbuf[BUF]; // temp storage for file read
myReadFile.open("listOwords.txt");
if(!myReadFile) {
cerr << "Error: file could not be opened" << endl;
exit(1);
}
cout << "file opened successfully" << endl;
while(myReadFile.getline(sbuf, BUF, ',')) {
pair.first = sbuf;
myReadFile.getline(sbuf, BUF);
pair.second = sbuf;
if(myReadFile.good()) {
// only process if both elements were read successfully
// this deals with the problem of a "half pair" being read if the file is terminated with \n
startTape.push_back(pair);
cout << "read a pair: " << pair.first << ", " << pair.second << endl;
}
}
myReadFile.close();
cout << "Size of startTape is now " << startTape.size() << endl;
std::pair<std::string,std::string> firstCompare = startTape.front();
startTape.remove(*startTape.begin());
cout << "Size of startTape is now " << startTape.size() << endl;
std::pair<std::string,std::string> secondCompare = startTape.front();
startTape.remove(*startTape.begin());
cout << "Size of startTape is now " << startTape.size() << endl;
exit(0);
}
listOwords 的内容:
>cat listOwords.txt
N, C
I, G
A, U
H, A
G, M
C, I
S, H
U, N
我从中得到的输出是:
file opened successfully
read a pair: N, C
read a pair: I, G
read a pair: A, U
read a pair: H, A
read a pair: G, M
read a pair: C, I
read a pair: S, H
read a pair: U, N
Size of startTape is now 8
Size of startTape is now 7
Size of startTape is now 6
如果您使用此确切代码没有得到相同的结果,请告诉我?