[英]file reading in c++: for and while nested loop are not working as expected: serially?
我希望嵌套的for循環按序列順序工作,例如考慮以下代碼:
int main ()
{
string mainstr;
ifstream infile;
ifstream infile1;
infile.open ("27032015.log");
infile1.open("Exordernumber");
for (unsigned int curLine = 0; getline(infile1,exordernum); curLine++)
{
cout << "curLine:" << curLine << endl;
{
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
cout << "curLine1:" << curLine1 << endl;
if (mainstr.find(exordernum) != std::string::npos)
{
cout << "exordernum:"<<exordernum << ":" << endl;
}
}
}
我希望它首先打印curLine:1
然后curLine1:{所有值}
然后curLine:2
然后curLine1:{所有值}
然后curLine:3
然后curLine1:{所有值}
等等..
但它打印出的東西:
curLine:1
然后curLine1:{所有值}
curLine:2
curLine:3
curLine:4
等等..
錯誤在哪里?
即使我使用while循環,也會打印出相同的內容。
我不知道問題所在。
現在問題已解決,我想知道同一件事的python代碼:這是我編寫的內容,它給出了錯誤。
#!/usr/bin/env python
import sys
import re
hand = open('Exordernumber')
for line1 in hand:
with open('27032015.log') as f:
for line in f:
if re.search(line,line1):
print line
f.close()
請提出正確的python代碼。
第一次轉到文件“ 27032015.log”的末尾。 第二次您將永遠不會去循環:
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
cout << "curLine1:" << curLine1 << endl;
您必須將光標置於文件的開頭或在循環末尾重新打開它。
int main ()
{
string mainstr;
ifstream infile;
ifstream infile1;
infile.open ("27032015.log");
infile1.open("Exordernumber");
for (unsigned int curLine = 0; getline(infile1,exordernum); curLine++)
{
cout << "curLine:" << curLine << endl;
{
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
cout << "curLine1:" << curLine1 << endl;
if (mainstr.find(exordernum) != std::string::npos)
{
cout << "exordernum:"<<exordernum << ":" << endl;
}
infile.seekg (0, infile.beg);
}
}
您必須在每次外部迭代后將文件內流重置為流的開頭。 我想你需要這樣的東西
for (unsigned int curLine = 0; getline(infile1,exordernum); curLine++)
{
cout << "curLine:" << curLine << endl;
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
{
cout << "curLine1:" << curLine1 << endl;
if (mainstr.find(exordernum) != std::string::npos)
{
cout << "exordernum:"<<exordernum << ":" << endl;
}
}
infile.seekg (0, infile.beg);
}
進入內部循環僅一次,因為第一次循環訪問該文件后,該循環“ getline(infile,mainstr)”的條件就不再滿足。 文件中的指針始終指向文件末尾。
您可以做的是在外部循環中打開文件:
for (unsigned int curLine = 0; getline(infile1,exordernum); curLine++)
{
cout << "curLine:" << curLine << endl;
infile.open ("27032015.log");
{
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
cout << "curLine1:" << curLine1 << endl;
if (mainstr.find(exordernum) != std::string::npos)
{
cout << "exordernum:"<<exordernum << ":" << endl;
}
}
infile.close ();
}
因此,輸入文件將在進入內部循環之前每次都重新初始化。
對於python代碼,您可以嘗試刪除最后一行'f.close()'。 當您使用“ with open”時,python將為您處理文件關閉。 但是您需要手動關閉文件“ hand”。
#!/usr/bin/env python
import sys
import re
hand = open('Exordernumber')
for line1 in hand:
with open('27032015.log') as f:
for line in f:
if re.search(line,line1):
print line
hand.close()
您可以發布python代碼的錯誤消息嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.