-1

我基本上是在读取.txt文件并存储值。

例如:

Student- Mark
Tennis

它将Mark作为studentName.

现在……如果只是

Student-
Tennis

然后它将正常工作并产生错误。

但是,如果文件看起来像这样

Student-(space)(nothing here)
Tennis

它将作为 存储Tennis到内存中studentName,如果事实上它不应该存储任何内容并产生错误。我使用'\n'字符来确定字符之后是否有任何内容-。这是我的代码...

istream& operator>> (istream& is, Student& student)
{   
    is.get(buffer,200,'-');
    is.get(ch);
    if(is.peek() == '\n')
    {
        cout << "Nothing there" << endl;
    }
    is >> ws;
    is.getline(student.studentName, 75);
}

我认为这是因为is.peek()正在识别空格,但是如果我尝试使用 删除空格is >> ws,它会删除'\n'字符并仍然存储TennisstudentName.

如果有人可以帮助我解决这个问题,那真的意义重大。

4

2 回答 2

0

如果你想忽略空格但你不能轻易使用 它会跳过所有空格,除了字符(换行符)、(制表符)和(回车)被认为是空格(我认为实际上甚至还有几个)。您可以重新定义空白对您的流意味着什么(通过用自定义方面替换流,这改变了空白意味着什么)但这可能更高级(据我所知,大约有少数人可以马上做;问一下,如果我注意到它,我会回答这个问题,不过......)。一种更简单的方法是使用简单地读取行尾并查看其中的内容。'\n'std::ws' ''\n''\t''\r'std::localestd::ctype<char>std::getline()

另一种选择是创建自己的操纵器,比如说,skipspace并在检查换行符之前使用它:

std::istream& skipspace(std::istream& in) {
    std::istreambuf_iterator<char> it(in), end;
    std::find_if(it, end, [](char c){ return c != ' '; });
    return in;
}
// ...
if ((in >> skipspace).peek() != '\n') {
    // ....
}
于 2014-12-17T23:14:53.650 回答
0

你不需要偷看字符。我会使用std::getline()并让它为您处理换行符,然后std::istringstream用于解析:

std::istream& operator>> (std::istream& is, Student& student)
{   
    std::string line;
    if (!std::getline(is, line))
    {
        std::cout << "Can't read student name" << std::endl;
        return is;
    }

    std::istringstream iss(line);
    std::string ignore;
    std::getline(iss, ignore, '-');
    iss >> std::ws;
    iss.getline(student.studentName, 75);

    /*
    read and store className if needed ... 

    if (!std::getline(is, line))
    {
        std::cout << "Can't read class name" << std::endl;
        return is;
    }

    std::istringstream iss2(line);
    iss2.getline(student.className, ...);
    */

    return is;
}

或者,如果您可以更改Student::studentName为 astd::string而不是 a char[]

std::istream& operator>> (std::istream& is, Student& student)
{   
    std::string line;
    if (!std::getline(is, line))
    {
        std::cout << "Can't read student name" << std::endl;
        return is;
    }

    std::istringstream iss(line);
    std::string ignore;
    std::getline(iss, ignore, '-');
    iss >> std::ws >> student.studentName;

    /*
    read and store className if needed ... 

    if (!std::getline(is, student.className))
    {
        std::cout << "Can't read class name" << std::endl;
        return is;
    }
    */

    return is;
}
于 2014-12-17T23:14:54.740 回答