簡體   English   中英

程序未在輸入文件中繼續進行讀取

[英]The program doesn't proceed inside the input file to read it

這些是我擁有的代碼的一部分:

ifstream inFile;
inFile.open("Product1.wrl");
...
if (!inFile.is_open()){
    cout << "Could not open file to read" << endl;
    return 0;
}
else 
    while(!inFile.eof()){
        getline(inFile, line);
        cout << line << endl;  //this statement only to chech the info stored in "line" string
        if (line.find("PointSet"))
            inFile >> Point1;
    }

輸出一遍又一遍顯示相同的字符串。 因此,這意味着文件內的光標不會繼續運行,並且getline讀取同一行。

這種奇怪行為可能是什么問題?

如果這是相關的:該文件確實以.txt文件打開,並且包含我需要的確切信息。

好的,我知道了問題所在:即使在第一次進行枚舉之后, line.find("PointSet")的返回值為:429467295 ...而我的line字符串僅包含一個字母“ S”。 為什么?

更改

while(!inFile.eof()){
    getline(inFile, line);

while( getline(inFile, line) ) {

我不知道為什么人們經常被eof()咬傷,但是他們確實如此。

getline>>混合是有問題的,因為>>將在流中留下一個'\\n' ,因此下一個getline將返回為空。 將其更改為也使用getline

if (line.find("PointSet"))也不是您想要的。 find返回string的位置,如果未找到,則返回std::string::npos

此外,您可以更改

ifstream inFile;
inFile.open("Product1.wrl");

ifstream inFile ("Product1.wrl");

這是顯示讀物的版本:

class Point 
{
public:
    int i, j;
};

template <typename CharT>
std::basic_istream<CharT>& operator>>
    (std::basic_istream<CharT>& is, Point& p)
{
    is >> p.i >> p.j;
    return is;
}

int main()
{
    Point point1;
    std::string line;
    while(std::getline(std::cin, line))
    {
        std::cout << line << '\n';  //this statement only to chech the info stored in "line" string
        if (line.find("PointSet") != std::string::npos)
        {
            std::string pointString;
            if (std::getline(std::cin, pointString))
            {
                std::istringstream iss(pointString);
                iss >> point1;
                std::cout << "Got point " << point1.i << ", " << point1.j << '\n';
            }
            else
            {
                std::cout << "Uhoh, forget to provide a line with a PointSet!\n";
            }
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM