无法读取文本文件C ++的内容

时间:2014-08-12 06:30:11

标签: c++ file-io visual-studio-2005

我在Socket.cpp中有以下代码 -

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include "CommandProcessor.h"

void main()
{
    CommandProcessor cp;
    cp.RetrieveTag();
    std::getchar();
}

函数RetrieveTag()如下 -

void CommandProcessor::RetrieveTag()
{
    std::ifstream file;
    std::string filename = "C:\Users\mraman\Desktop\input.txt";
    std::string str;
    std::string file_contents;
    file.open(filename.c_str());
    while (std::getline(file, str))
    {
        file_contents += str;
        file_contents.push_back('\n');
    }
    cout<<file_contents;
}

虽然input.txt包含数据,但是当我放置断点并进行调试时,它不会进入while循环本身,因此不会将文件内容显示为输出。

1 个答案:

答案 0 :(得分:4)

"C:\Users\mraman\Desktop\input.txt";应为"C:\\Users\\mraman\\Desktop\\input.txt";您需要转义字符串文字中的\

此外,您可能希望使用ifstream检查operator!的状态。

if( file ) { .... }
相关问题