如何逐行读取文件并分隔行组件?



我是C++新手(我通常使用Java(,并且正在尝试制作一个k-ary堆。我想将文件中的值插入到堆中;但是,我对我想做的事情的代码感到茫然。

我想像在 Java 中使用扫描仪一样使用.nextLine.hasNextLine,但我不确定这些是否适用于C++。此外,在文件中列出了以下项目:"IN 890""IN 9228""EX""IN 847"等。"IN"部分告诉我插入,"EX"部分是供我extract_min的。我不知道如何在C++中分隔字符串和整数,所以我可以只插入数字。

int main(){

BinaryMinHeap h;
string str ("IN");
string str ("EX");
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> x) {
sum = sum + x;
if(str.find(nextLin) == true //if "IN" is in line)
{
h.insertKey(nextLin); //insert the number 
}
else //if "EX" is in line perform extract min
}
inFile.close();
cout << "Sum = " << sum << endl; 
}

结果应该只是将数字添加到堆中或提取最小值。

查看各种std::istream实现 -std::ifstreamstd::istringstream等。您可以在循环中调用std::getline()以逐行读取std::ifstream,并使用std::istringstream来分析每一行。例如:

int main() {
BinaryMinHeap h;
string line, item;
int x sum = 0;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
return 1; // terminate with error
}
while (getline(inFile, line)) {
istringstream iss(line);
iss >> item;
if (item == "IN") {
iss >> x;
sum += x;
h.insertKey(x);
}
else if (item == "EX") {
// perform extract min
}
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}

最新更新