c++ - 使用 istringstream 丢失随机字符

标签 c++ c++11

我正在将文本文件的行读取到变量 myline 中,然后尝试使用 istringstream 标记这些行。但是,我似乎丢失了原始文本文件字符串中的随机字符。

cout<< myline << buff << flush; //print original text file line
istringstream iss(myline);
string sub;
while (iss >> sub) {
cout << "[" << sub << "]" << endl;
} 

如果您查看我的输出,您可以看到我从文本文件中获得了正确的字符串,但是当我使用 istringstream 然后打印各个标记(在 [] 括号内看到)时,某些标记被过早截断.

#include <iostream>
[#include]
[<iostream]
#include <sstream>
[#include]
[<sstream>]
using namespace std;
[using]
[namespace]
[st]

int main()
[int]
[main(]
{
    string str("   SOME  LONG    STRING\twith\nSPACES    ");
[string]
[str("]
[SOME]
[LONG]
[STRING\twith\nSPACES]

    istringstream iss(str);
[istringstream]
[iss(str);]

    string s;
[strin]
    while (iss >> s) {
[while]
[(iss]
[>>]
        cout << "[" << s << "]" << endl;
[cout]
[<<]
["["]
[<<]
[s]
[<<]
["]"]
[<<]
[e]
    }
    return 0;
[retur]
}

有人知道我做错了什么吗?提前致谢!

编辑:这是可以完全编译的代码版本。您可以使用任何文本文件运行它

#include <cstring>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

class MyFileReader {

public:
    //constructor
    MyFileReader(const char* p);

    //destructor
    ~MyFileReader();

    //getLine()
    int getLine(char *buffer, int size);

    //getCurrentLineNumber()
    int getCurrentLineNumber();

    void tokenizeLine(vector<string>& vec);

    FILE * pFile;

};

    //constructor
    MyFileReader::MyFileReader(const char* p) {
        pFile = fopen(p, "r");
    }

    //destructor
    MyFileReader::~MyFileReader() {
        fclose(pFile);
    }

    //getLine()
    int MyFileReader::getLine(char *buffer, int size){
        char *out = fgets(buffer, size, pFile);
        if (out==NULL) {
            return -1;
        }
        char *pch = strpbrk(out,"\n");
        if (pch != NULL) {
            return 1;
        }
        else {
            return 0;
        }

    }

    int MyFileReader::getCurrentLineNumber() {
        static int mynumber=2;
        return mynumber++;
    }

    //tokenizeLine
    void MyFileReader::tokenizeLine(vector<string>& vec) {
        string myline("");
        char buff[10];
        while (1) {
            int result = getLine(buff, sizeof(buff));
            if (result == -1 ) {
                if (myline.length() > 0) 
                    cout << myline << flush;
            break;
            }
            else if (result == 0) {
                myline += buff;
            }
            else if (result == 1) {
                cout<< myline << buff << flush;
                istringstream iss(myline);
                string sub;
                while (iss >> sub) {
                    cout << "[" << sub << "]" << endl;
                } 
                myline = "";
            }
            else {
                printf("PANIC");
            }
            }
            return;
        }

    int main(int argc, char **argv) {
    vector<string> v;

    const char *filename = argv[1];
    MyFileReader f(filename);
    f.tokenizeLine(v);
    return 0;

    }

为了生成上面的输出,我运行它:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string str("   SOME  LONG    STRING\twith\nSPACES    ");

    istringstream iss(str);

    string s;
    while (iss >> s) {
        cout << "[" << s << "]" << endl;
    }
    return 0;
}

最佳答案

错误在这里:

else if (result == 1) {
            cout<< myline << buff << flush;
            istringstream iss(myline);
            string sub;
            while (iss >> sub) {
                cout << "[" << sub << "]" << endl;
            } 
            myline = "";
        }

如果result == 1 ,这意味着 buff 包含 \n ,这并不意味着它包含 \n 。 IE。如果缓冲区包含 \n,则将其删除。因此,如果该行恰好有 n*10 (sizeof buffer) 个字符,则您的代码可以工作,否则,该行的最后一个字符不会复制到 myline但放弃了。

快速解决方法是:

    else if (result == 1) {
            myline += buff; // copy the rest of the line into `myline`
            cout<< myline << flush; // buff now is part of myline
            istringstream iss(myline);
            string sub;
            while (iss >> sub) {
                cout << "[" << sub << "]" << endl;
            } 
            myline = "";
        }

尽管您可能需要考虑删除 \n从缓冲区中,例如:

int MyFileReader::getLine(char *buffer, int size){
    char *out = fgets(buffer, size, pFile);
    if (out==NULL) {
        return -1;
    }
    //char *pch = strpbrk(out,"\n");
    char *pch = strchr(out,'\n'); // no need to search for a string
    if (pch != NULL) {
        *pch = '\0'; // drop the '\n'
        return 1;
    }
    else {
        return 0;
    }

}

您必须更改cout<< myline << flush;cout<< myline << endl;不过。


除了这个错误,请考虑使用 ifstream :

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main()
{
    ifstream file("test.txt");
    if(!file)
    {
        /* error */
    }else
    {
        string line;
        while(getline(file, line))
        {
            istringstream iss(line);

            string s;
            while (iss >> s) {
                cout << "[" << s << "]" << endl;
            }
        }
    }
}

关于c++ - 使用 istringstream 丢失随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368051/

相关文章:

c++ - 指向对象的指针的私有(private) vector 。如何使用 getter 方法访问这些对象?

c++ - 使用单独的线程从文件预加载数据

c++ - 智能指针控制 block 内部机械

c++ - SFML UdpSockets 没有发送/接收没有错误?

c++ - 原始类型的 emplace_back 与 push_back

c++ - 如果模板类型是另一个模板则运行代码

c++ - 具有初始值的类构造

多维动态数组中的 C++ 对象构造

c++ - qwt plot曲线轴不可见

c++ - 虚拟赋值运算符不允许 static_cast