如果文件包含长单词(不是极端的),ifstream 会导致程序崩溃

ifstream crashing program if file contains long words (not extreme)

我遇到了这种奇怪的情况 - 我正在尝试从文件中读取单词。

#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>

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

    if (argc != 2) {
        std::cout << "bad number of arguments" << std::endl;
        return 1;
    } 

    std::cout << "trying to open file: " << argv[1] << std::endl;

    ifstream fin(argv[1]);
    std::cout<< "this is a test string" << std::endl;

    if (!fin) {
        std::cout << "Could not open file" << std::endl;
        return 1;
    }

    string word;
    while (fin >> word) {
        std::cout << word << std::endl;
    }

    return 0;
}

崩溃的输入是:(这些词没有逻辑意义,只是一堆词)

the man row in front turned when he heard his name
called but had no idea who called him
and was worried maybe police were looking for
so ran hid car
lock master frame card muffin 
pancake their pasta shuttle glass
remote where answer chair table
laptop phone key window paper abcdefghijkmop

文件名作为参数传递(显然)并且文件肯定存在于正确的位置。

我的文件有 50 个字。试图打开文件会导致它崩溃,它甚至无法打印我输入的测试字符串。

奇怪的是 - 当我删除一些单词(只留下 36 个单词)时,它起作用了。当我再添加一个词时 - 它崩溃了。

我尝试检查格式、空格和换行符,使用了多个文本编辑器 - 没有任何效果。如您所见,它主要是第一个,所以我想没有什么会导致这个问题。

我尝试检查其他线程 like this or this 但没有成功找到解决方案。

请帮我解决这个问题——让我抓狂的是,在文件中添加超过 36 个单词的单词会使程序崩溃,但如果单词数量不超过这个数量——它会按预期工作。我感觉到它有一些我想念的格式错误,但我只是不知道是什么。

我正在使用 windows 7,visual studio 2013 如果有帮助的话。

更新:我尝试了另一个使用较长单词的示例,我注意到当我删除较长的单词时,它起作用了,所以问题可能出在单词长度上。但是,我使用了 "string word"。这可能是个问题吗? (更长的时间我的意思是像 "population",不是极端的东西)

由于您使用的是 C++,因此您应该坚持使用 C++ 标准库 I/O headers:

#include <iostream>
#include <fstream>

old-style C header是

#include <stdio.h>

"stdio.h" 的 C++ 兼容性 header 是

#include <cstdio>

出于某种原因,我不明白混合使用 <iostream><stdio.h> 在 Visual Studio 2013 下会导致问题。

我很高兴删除 <stdio.h> 解决了您的问题,即使这只是一种预感,我无法从根本原因上启发您。