繁体   English   中英

从文件中读取cin不起作用

[英]Reading cin from a file not working

我正在开发一个项目,我必须使用命令行重定向从文本文件中读取字典(即 ./myprog myargs < in.txt)

然后我将 cin 传递给一个函数来构造一个字典对象。

int main(int argc, char *argv[]) {

Dictionary all_words(std::cin);
Dictionary solution;
std::deque <Word> possible_additions;

std::cout << all_words[0].get_word() << " this is a word" << '\n';

opterr = true;
static struct option longopts[] = {
    { "stack",    no_argument,       nullptr,    's' },
    { "queue",    no_argument,       nullptr,    'q' },
    { "change",   no_argument,       nullptr,    'c' },
    { "swap",     no_argument,       nullptr,    'p' },

等等。

Dictionary::Dictionary(std::istream& is) {
char type;
int size;
std::string line;
int i = 0;

is >> type >> size;

words.reserve(size);

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

    if (type == 's') {
        if ((line.length() == 0 || line[0] == '/') &&
            (line.length() == 0 || line[1] == '/'))
        {
            continue;
        }

        else {
            std::cout << line << '\n';
            words.push_back(line);
            ++i;
        }
    }

我的问题是字典中没有添加任何内容。 但是,如果我用文件名的 ifstream 初始化字典,它工作正常。

IE:

Dictionary a;
std::ifstream testFile;
testFile.open("simple-dict.txt");
Dictionary b(testFile);

工作正常并构建字典。

我在使用 MSVS 时没有遇到这个问题,但是现在我使用的是 gcc 它似乎不起作用。

谢谢你的帮助!

看起来是 eof()。 从未意识到它可能导致的问题。 将其更改为 getline(is, line) 修复它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM