簡體   English   中英

[C ++]導入文本文件 - getline()問題

[英][C++]Importing text file - Problems with getline()

我在使用c ++讀取文本文件時遇到了麻煩,特別是在為變量分配行時。

我有以下代碼:

ifstream fx;
fx.open(nomeFich);
if(!fx)
{cout << "FX. nao existe!" <<endl;}
string linha="";;
int pos, inic;

while(!fx.eof())
{
    getline(fx,linha);

    if(linha.size() > 0)
    {
        cout << linha << endl;
        inic=0;
        pos=0;
        pos=linha.find(",",inic);
        cout << pos << endl;
        string nomeL1(linha.substr(inic,pos));
        cout << "atribuiu 1" << endl;
        inic=pos;

        cout <<"inic: " << inic << "      pos:" << pos <<endl;

        pos=linha.find(',',inic);
        string nomeL2(linha.substr(inic,pos));
        cout << "atribuiu 2" << endl;
        inic=pos;

        cout <<"inic: " << inic << "      pos:" << pos <<endl;

        pos=linha.find(',',inic);
        cout << "atribuiu 3" << endl;
        string dist(linha.substr(inic,pos));

當它做cout << linha << endl; 它返回類似於:

= = == = = = = == = = = = = = = = = = = = = = = = = = = = =

我用谷歌搜索了很多,但找不到答案。 我是C ++的新手,所以不要過多地使用xD

不要這樣做:

while(!fx.eof())
{
    getline(fx,linha);   // Here you have to check if getline() actually succeded
                         // before you do any further processing.
                         // You could add if (!fx) { break;}

    // STUFF;
}

但更好的設計是:

while(getline(fx,linha))  // If the read works then enter the loop otherwise don't
{
    // STUFF
}

你沒有超越逗號:

inic=pos;                  // pos is the position of the last ',' or std::string::npos
pos=linha.find(',',inic);  // So here pos will be the same as last time.
                           // As you start searching from a position that has a comma.

ifstream有一個getline函數,它接受char*作為第一個參數,最大長度作為第二個參數。

ifstream還有你應該用於輸入的operator>> ,但它會讀到空白,這不是你想要的。

你正在使用的::getline也應該有效,但是假設流是正常的,如前所述,你沒有正確檢查。 您應該在調用之后檢查錯誤,因為如果您達到EOF或出現錯誤,您將無法知道,直到整個循環完成。

另外,文件中有什么? 也許你得到的是正確的結果?

暫無
暫無

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

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