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

时间:2015-03-09 04:15:17

标签: c++ fstream ifstream

我有这种奇怪的情况 - 我试图从文件中读取文字。

#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 thisthis,但未找到解决方案。

请帮我解决这个问题 - 让我发疯的是,在文件中添加一个单词超过36个单词会使程序崩溃,但是使用这个单词或更少的单词 - 它会按预期工作。我感觉到它错过了一些格式错误,但我不知道是什么。

我正在使用Windows 7,Visual Studio 2013,如果有帮助的话。

更新:我尝试了另一个更长的单词的例子,我注意到当我删除较长的单词时,它可以工作,所以问题可能是单词长度。但是,我使用了“字符串”。这可能是个问题吗? (更长的我的意思是“人口”,而不是极端的东西)

1 个答案:

答案 0 :(得分:0)

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

#include <iostream>
#include <fstream>

旧式C标头是

#include <stdio.h>

“stdio.h”的C ++兼容性标题是

#include <cstdio>

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

我很高兴删除<stdio.h>修复你的问题,即使这只是一种预感,我无法通过根本原因启发你。