Problem Using ifstream; Strange Characters Appearing

Aug 16, 2013 at 6:48pm
Hello, I am trying to read a file containing two lines of text, like such:
UserName
HOST\Owner

The text was written to a text file named "CompNames.txt" by a batch file, and it appears just as above. When I attempt to read it using ifstream, it prints the text of the second line of the file to another file names "op.txt" (as expected); however each character is separated by a box, which appears to signify that there were characters that the output could not read, I can't copy and paste this, but it most closely resembles:
☐H☐O☐S☐T☐O☐w☐n☐e☐r☐☐☐
☐::cname

I searched forums for a while and found numerous occurrences of this happening at the end of a line or file but never in the midst of one. Here is a snippet of my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  ifstream names ("CompNames.txt");									
  if (!names.is_open()) {
    report(error("Could not open CompNames.txt", "Search Bar", 2)); 
    //the above is defined, I assure you
    return;
  }
  string cname;
  size_t pos, slash;
  while (getline(names, cname)) {
    slash = cname.find("\\");
    if (slash == string::npos) {
      continue:
    }		       								       			  
    cname.erase(slash, 1);
    pos = cname.find(name);  
    ofstream out;
    out.open("op.txt");	
    if (out.is_open()) {
      out << cname + "::cname\n";
      out.close();
    }	
    names.close();
  }


I should also mention that I am using Visual C++.
What am I doing wrong here? Thank you for your time.
Last edited on Aug 16, 2013 at 6:51pm
Aug 16, 2013 at 7:00pm
There are two lines of text in your source file. You are trying to save these lines to a single string called cname.

cname should be an array of strings to hold multiple lines of text.

This is my guess.
Aug 16, 2013 at 7:01pm
By the looks of it, your file is stored using UTF-16 encoding, but you're reading it using plain (non-converting) std::ifstream

Since you're using Visual C++, you can either use standard utf16 conversion functions from the header <codecvt> or use Microsoft's _O_U16TEXT file mode. Either way, you'll be reading into a wide characters string. Or perhaps it would be easier to save the file in a single-byte encoding.
Last edited on Aug 16, 2013 at 7:06pm
Aug 16, 2013 at 8:11pm
Thank you Cubbi. I never considered the files encoding as the problem! I simply altered the file's encoding to ANSI, which took care of the problem.
Topic archived. No new replies allowed.