Cin newline space problem... or something

This is a discussion on Cin newline space problem... or something within the C++ Programming forums, part of the General Programming Boards category; For my first C++ program, I made a little text editor for the sake of understanding the whole fopen stuff. ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    9

    Cin newline space problem... or something

    For my first C++ program, I made a little text editor for the sake of understanding the whole fopen stuff. With my background knowledge of PHP this is going rather well, but I have encountered a problem.

    Code:
    #include<iostream.h>
    #include<cstdio>
    #include<string>
    
    void main () {
     cout<<"Welcome to FedEdit...\n";
     char filename[255];
     cout<<"Please enter the file path to open. \nNote that it will be interpreted as a textfile\nKeep it small, yes?\n";
     cin>>filename;
     cout<<"You chose "<<filename<<"\n\n";
     FILE * filePointer;
     filePointer = fopen(filename,"r+");
     if(filePointer) {
      cout<<"File Contents:\n\n";
      char line[81];
      char *return_code;
    
      while(!feof(filePointer)) {
       return_code = fgets(line, 80, filePointer);
       cout<<line;
      }
      cout<<"\n\n--------------------------\nOkay, now enter new file content:\n";
      cout<<"a line only containing a period will end the writing mode.";
      cout<<"please do not enter more than 80 characters per line. thank you.\n\n--------------------\n";
      char newline[81];
      rewind(filePointer);
      while(strcmp(newline,".")) {
       cin>>newline;
       if(strcmp(newline,".")) {
        fputs(newline,filePointer);
        fputs("\r\n",filePointer);
       }
      }
      fclose(filePointer);
     } else cout<<"ERRORZ";
     
    }
    this is the source. Basicially, you open a file of choice, it echoes it, and then you re-write it. The problem?

    Well, it interprets spaces as newlines. Actually, it doesn't.
    Code:
      while(strcmp(newline,".")) {
       cin>>newline;
       if(strcmp(newline,".")) {
        fputs(newline,filePointer);
        fputs("\r\n",filePointer);
       }
      }
    see that part?

    well that's the problem. Apparently, when encountering a space, the loop re-loops with the next word, causing
    Code:
        fputs("\r\n",filePointer);
    to render it as new line.


    Now, why is this happening, how do I fix this?

    Any other suggestions for a better way of coding are appreaciated as well!
    I'm a beginner, sorry.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Code:
    #include<iostream.h>
    Bad. Use <iostream>.

    Code:
    #include<string>
    Bad. The only string function I see you using is strcmp, which is in <string.h> or <cstring>. <string> is for the std::string class - which you should be using instead of the raw C strings.

    Code:
    void main () {
    Bad. main() returns int.

    Code:
    char filename[255];
    Bad. As I said above, use std::string.

    Code:
    cin>>filename;
    Bad. >> stops at spaces, so you can't enter a filename with spaces here. And of course there's the danger of overflow for long names. Use std::string and getline:
    Code:
    std::string filename;
    std::getline(std::cin, filename);
    Code:
     FILE * filePointer;
     filePointer = fopen(filename,"r+");
    Bad. First, why are you using C-style file I/O when you're using C++-style console I/O? Second, you open the file in text mode, yet further down you mess with raw \r signs. Under Unix, that will lead to \r characters in the file that don't belong there at all. Under Windows, it will lead to duplicated \r characters. (One explicitly and another when the stream converts the \n.)

    Code:
    char line[81];
    Very small buffer. Use std::string.

    Code:
    char *return_code;
    Variable is never read from.

    Code:
    while(!feof(filePointer)) {
    Bad. See the FAQ for why feof() is a bad loop condition. The gist is, if there's a read error, your code will loop forever.

    Code:
    while(strcmp(newline,".")) {
    Bad. newline is uninitialized, so you don't know what's in there. For all you know, this will be false the first time around. Also, as a matter of personal style, always compare the result of strcmp() against an actual integer. It is unintuitive to have the strcmp() stand alone in a condition, because the boolean conversion yields false if the strings actually are equal.

    Code:
    cin>>newline;
    Your actual problem. >> stops on any whitespace. You need getline().

    Code:
    fputs("\r\n",filePointer);
    You opened the file in text mode. Stick with a single \n.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    9
    Well, wow. Thanks for that, I guess.

    I know about the int main(), but it would return an error when I tried doing that originally.

    same goes for the iostream without the .h


    I originally used <string.h> but this guy told me to use <string> instead.

    Well, I'll get right on to fixing everything as you said, and you also put light on my problem. Thanks for that! I'll probably edit this post, or make a new post after I'm done.

    Thanks a lot!

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    I know about the int main(), but it would return an error when I tried doing that originally.

    same goes for the iostream without the .h
    Which compiler do you use?
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Registered User
    Join Date
    Oct 2007
    Posts
    9
    Visual C++ 6. Oddly enough, it worked this time. I guess I misspelled it or something, I have no idea.

    However, I have yet another problem
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    int main () {
    
    
     cout<<"Welcome to FedEdit...\n";
     string filename;
     cout<<"Please enter the file path to open. \nNote that it will be interpreted as a textfile\nKeep it small, yes?\n";
     getline (cin,filename);
     cout<<"You chose "<<filename<<"\n\n";
    
     ifstream myfile;
    
     myfile.open (filename);
     if(!myfile.fail()) {
    
      cout<<"File Contents:\n\n";
     /*
      string line;
    
      while(!feof(filePointer)) {
       fgets(line, 80, filePointer);
       cout<<line;
      }
      cout<<"\n\n--------------------------\nOkay, now enter new file content:\n";
      cout<<"a line only containing a period will end the writing mode.";
      cout<<"please do not enter more than 80 characters per line. thank you.\n\n--------------------\n";
      char newline[81];
      rewind(filePointer);
      while(strcmp(newline,".")) {
       cin>>newline;
       if(strcmp(newline,".")) {
        fputs(newline,filePointer);
    	fputs("\r\n",filePointer);
       }
      }
      fclose(filePointer);
    	 */
     } else cout<<"ERRORZ";
     
    
    }
    
    // getline with strings
    this is how far I got converting the code to proper code, but at this point it gives me the error:

    C:\Program Files\Microsoft Visual Studio\MyProjects\jkhjk\asfd.cpp(18) : error C2664: 'void __thiscall std::basic_ifstream<char,struct std::char_traits<char> >:pen(const char *,int)' : cannot convert parameter 1 from 'class std::basic_string<char,
    struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
    No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
    as well as the warning (here we go again...)
    C:\Program Files\Microsoft Visual Studio\MyProjects\jkhjk\asfd.cpp(46) : warning C4508: 'main' : function should return a value; 'void' return type assumed
    Error executing cl.exe.
    but is main() really supposed to return anything?

    And more importantly, what's up with the first thing?

    I had some more errors, but I was able to fix those myself...

  6. #6
    Registered User
    Join Date
    Oct 2007
    Posts
    66
    To my knowledge you can not use fopen with std::string as it is a c-style function and expects a cstring.

    As far as your warning goes, as it says you need to return something in main.

    Code:
    int main()
    {
            ...
            return 0;    // Instead of 0 use EXIT_SUCCESS if you #include <windows.h>
    }

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,802
    The error tells you exactly what is happening, your open call is expecting a const char* but you're passing it a string. Unfortunately, the ifstream's open member function does not accept a string as an argument (something which I believe is being considered for the future). Fortunately, string objects have a member function (c_str()) which returns exactly what you want:
    Code:
    myfile.open(filename.c_str());
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  8. #8
    Registered User
    Join Date
    Oct 2007
    Posts
    9
    Yeah, I knew the error, I just didn't know how to fix it.

    Well, thanks hk_mp5kpdw! That worked! I will convert the rest as soon as I get home from school.
    Last edited by Baqualish; 10-07-2007 at 11:34 PM.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    VC++6 is nearly 10 years old and severely lacks in standard conformance. You really ought to upgrade. VC++2005 is free.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Oct 2007
    Posts
    9
    A friend gave it to me... Well, if it's free, then I'll look into it. Good thing somebody tells me that before I get used to the compiler.

    Thanks once again, CornedBee!

  11. #11
    Registered User
    Join Date
    Oct 2007
    Posts
    9
    Well, I finally got around to re-writing this thing, but now I have a problem I don't quite understand.

    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    int main () {
    
    
     cout<<"Welcome to FedEdit...\n";
     string filename;
     cout<<"Please enter the file path to open. \nNote that it will be interpreted as a textfile\nKeep it small, yes?\n";
     getline (cin,filename);
     cout<<"You chose "<<filename<<"\n\n";
    
     fstream myfile;
    
     myfile.open (filename.c_str(),ios::binary | fstream::in | fstream::out );
     if(!myfile.fail()) {
    
      cout<<"File Contents:\n\n";
     
    
    
      int length;
    
    
      myfile.seekg (0, ios::end);
      length = myfile.tellg();
      myfile.seekg (0, ios::beg);
      char *fcontent;
      fcontent = new char [length];
    
      myfile.read(fcontent,length);
    
      cout<<"The file is "<<length<<"bytes long; file conent:\n";
      cout.write(fcontent,length);
    
    
      cout<<"\n\n--------------------------\nOkay, now enter new file content:\n";
      cout<<"a line only containing a period will end the writing mode.";
      cout<<"please do not enter more than 80 characters per line. thank you.\n\n--------------------\n";
    
     string newline = "";
    
      while(newline != ".") {
       getline (cin,newline);
       if(newline != ".") {
        myfile.write(newline.c_str(),strlen(newline.c_str()));
       }
      }
      
    
    	 
     } else cout<<"ERRORZ";
     
     return 0;
    }
    Everything works fine so far, except for the fact that it simply doesn't write to the file, and I don't know why.

    Thanks for your patience, I really appreaciate it.
    Last edited by Baqualish; 10-17-2007 at 03:57 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with cin
    By IEatGreyFoxes in forum C++ Programming
    Replies: 4
    Last Post: 03-28-2004, 11:11 PM
  2. cin problem
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 03-14-2004, 02:23 AM
  3. a problem with cin......
    By werdy666 in forum C++ Programming
    Replies: 10
    Last Post: 09-17-2002, 12:05 AM
  4. problem with cin
    By wjday in forum C++ Programming
    Replies: 8
    Last Post: 07-09-2002, 11:04 AM
  5. Can't spot the problem...am i even on the right track?
    By iluvmyafboys in forum C++ Programming
    Replies: 8
    Last Post: 02-05-2002, 08:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21