简体   繁体   中英

Unable to read contents of Text File C++

I have the following code in Socket.cpp -

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

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

And the function RetrieveTag() is as follows -

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;
}

Though input.txt contains data, when I put a breakpoint and debug, it doesn't go into the while loop itself and hence doesn't display the file contents as output.

"C:\\Users\\mraman\\Desktop\\input.txt"; should be "C:\\\\Users\\\\mraman\\\\Desktop\\\\input.txt"; You need to escape the \\ in the string literal.

Also, you might want to check the state of the ifstream by using the operator! .

if( file ) { .... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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