Thread: Almost there...

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    21

    Almost there...

    Ok. I know you told me to try a simpler program to learn I/O and using files, and I have! There is one problem. In my program, all i ask is for them to input one letter, and in another program I ask it to show that letter. All it does is show nothing or one of those ||= thingies!
    Here is the program where they ask for the letter:
    Code:
    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    
    int main()
    {
    	char a[2];
    
    	cout<<"Hello, and welcome to my first try at real File I/O learning!\n";
    	cout<<"\nNow enter any letter of the English alphabet: ";
    	cin.get(a, 2);
    	ofstream stuff("firsttry.txt", ios::out);
    	stuff<<a;
    	stuff.close();
    	system("PAUSE");
    	return 0;
    }
    and here is the one where it shows the letter:
    Code:
    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    
    int main()
    {
    	char ch;
    
    	ifstream openstuff("firsttry.txt", ios::in);
    	openstuff.get(ch);
    	cout<<ch;
    	system("PAUSE");
    	return 0;
    }
    I am sorry for annoying you again. After I get the hang of this I should be able to stop bugging you.
    Last edited by shadowsora15; 06-01-2007 at 05:43 PM. Reason: My code tags were mis-spelled on accident

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Your program appears to work for me. I can't spot any errors.

    I do wonder, though.... If you're reading a char from the user in the first program, why not just pass cin.get() one char instead of a C-style string?

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Probably cout is buffering. Flush it before you call PAUSE

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    I don't know why you're getting the error, but you did forget to close the openstuff ifstream.

  5. #5
    Registered User pronecracker's Avatar
    Join Date
    Oct 2006
    Location
    netherlands
    Posts
    158
    Quote Originally Posted by robwhit View Post
    I don't know why you're getting the error, but you did forget to close the openstuff ifstream.
    You don't have to, it happens automatically when the destructor is called.
    Don't call me stupid.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by pronecracker View Post
    You don't have to, it happens automatically when the destructor is called.
    oh yeah... forgot about that.

    cin.get treats a as a null-terminated string.

    in cin.get(a, i);, a[i-1] is a null value. except, I guess, if i=0.

Popular pages Recent additions subscribe to a feed