C++ ifstream problem

Hi everyone.

I'm having a problem when my program try to read out a number from my .txt or rtf. file.

Can you take a look at my code and tell me why am I getting zero instead of the number inside my .txt file ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cctype>
#include <fstream>
#include <cstdlib>


using namespace std;

int main(){
    
    ifstream infile; // (ifstream) For the infile.fail
    
    infile.open("/Users/ha/Desktop/Everything/Kishwaukee/CS 240/Program 6/Program 6/password.rtf");
    
    
    
    if( infile.fail() )       //if the input file failed to open
    {
        cout << "input file did not open" << endl;
        exit(1);                //stop execution of the program immediately
    }
    
    int ch;
    
    infile >> ch;

    
    
    cout << "The number is: " << ch << endl;
    
    infile.close();
    
    return 0;
}
Last edited on
If the first expression in the text file does not represent a number the infile will fail. You should check that.

Line 17 should be is_open() instead of fail()
closed account (E0p9LyTq)
How is your number stored in your .rtf/.txt file?

I suspect it is stored as a string of characters, so you should read the file into a C++ string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

int main()
{
   std::ifstream infile; // (ifstream) For the infile.fail

   infile.open("/Users/ha/Desktop/Everything/Kishwaukee/CS 240/Program 6/Program 6/password.rtf");

   if( infile.fail() )       //if the input file failed to open
   {
      std::cout << "input file did not open\n";
      exit(1);                //stop execution of the program immediately
   }

   std::string ch;
   std::getline(infile, ch);

   std::cout << "The number is: " << ch << "\n";

   infile.close();
}
It is a number. I put only one number which is 7 in the text file.

Line 17 is correct.
closed account (E0p9LyTq)
You are not opening a text file (.txt), you are opening a rich-text file (.rtf).
I tried using both .txt and .rtf since I'm using a Mac.

try my code using a txt. file and type number 7 in it and see what you get.
Last edited on
When you write 1234 to a rtf file the file will contain:
1
2
3
4
{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
{\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 1234\par
}
 

When you try to read from it it will be junk.
Topic archived. No new replies allowed.