Dudearoo
Useing Code::Blocks

ok, ive got a somewhat simple error that i cant crack, First heres my code.

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <stdlib.h>
#include <iomanip>
#include <windows.h>
// so to use strcmp
#include <cstring>
#include <fstream>
using namespace std;

int main()
{

    ofstream myfile ("savefile.txt", ios::ate | ios::in | ios::trunc | ios::out);

    char stringsaveT[90];
    string question;

    if (myfile.is_open())
    {
        cout << "This is a .txt file save test.\n please type in a string of characters, and close the program\n once you open the program\n please type in open. " << endl;
        cout << "" << endl;
        cin >> question;
        if (question == "open")
        {
                myfile >> stringsaveT[90];
                cout << stringsaveT[90] << endl;


        }
        else if (question == "print")
        {
            cout << "  Please Type the string you want to save." << endl;
            cin >> stringsaveT;
            myfile << "  "<< stringsaveT <<" ";
        }



        myfile.close();
    }

    cout << "Last Cout! program reverts here first? and closes!" << endl;
    return 0;
}

all i want to do is to read the data from savefile.txt, ok so here's my error code
FILESAVETEST\main.cpp|29|error: no match for 'operator>>' in 'myfile >> stringsaveT[90]'|
i cant figure out the problem, heres where i got a refrence for a part of the code, From youtube
i umderstand the error code just not what to put down instead then >>.
Thanks you guys!
:)

(by the way i finaly found out how to save error codes to my clipboard. LOL)

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <iomanip>
// so to use strcmp
#include <cstring>
#include <fstream>
using namespace std;

int main()
{

    fstream myfile ("savefile.txt", ios::app | ios::in | ios::out);

    char stringsaveT[90];
    string question;


    if (myfile.is_open())
    {
        cout << "This is a .txt file save test.\n please type in a string of characters, and close the program\n once you open the program\n please type in open. " << endl;
        cout << "" << endl;
        cin >> question;
        if (question == "open")
        {
                myfile >> stringsaveT;
                cout << stringsaveT << endl;


        }
        else if (question == "print")
        {
            cout << "  Please Type the string you want to save." << endl;
            cin >> stringsaveT;
            myfile << "  "<< stringsaveT <<" ";
        }



        myfile.close();
    }

    cout << "Last Cout! program reverts here first? and closes!" << endl;
    return 0;
}

Use fstream, not ofstream since you are are reading AND writing to the file. That solves the >> operator problem. ofstream doesn't have one. fstream does.

The flags were incorrect. You don't want trunc if you are reading from the file because trunc wipes out the file, so I removed it. I replaced "ate" with "app". You want the file pointer to point to the end ONLY FOR WRITES. You want to READ from the beginning.

I took out the [90] when reading from the file. You are reading a STRING, not a character. You want to read a STRING into a BUFFER, not a CHARACTER into a single byte. TRy the code above and see if it does what you want.

hold on ill try it :)

IT WORKS! only one problem, now if i print for example "HELLO WORLD!" and then close and reopen the program, i want to open, i do so, and it only outputs "HELLO", well i looked at the .txt file and figured out that the program will only read and pull data from savefile.txt until a space, can you help me? VernonDozier by the way that example helped,
:)
please help me for this new issue that has rised.

What precisely are you trying to do? You are correct. >> reads until the first space. Do you want to read a full line? The entire file? If the former, consider using getline and also consider changing the type from character buffer to a string. The benefit of that is that you no longer have to worry about overrunning the buffer. Also notice that I added a cin.ignore line to the code. This may not be necessary, but can't hurt. The reason is that sometimes there is some "junk" left over in the input stream between the first inpuit and the second. cin.ignore cleans that up for a nice, fresh, clean stream. Give this program a whirl.

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <iomanip>
// so to use strcmp
#include <cstring>
#include <fstream>
using namespace std;

int main()
{

    fstream myfile ("savefile.txt", ios::app | ios::in | ios::out);

    string stringsaveT;
    string question;


    if (myfile.is_open())
    {
        cout << "This is a .txt file save test.\n please type in a string of characters, and close the program\n once you open the program\n please type in open. " << endl;
        cout << "" << endl;
        cin >> question;
        if (question == "open")
        {
                cin.ignore(256, '\n');
                getline(myfile, stringsaveT, '\n');
                cout << stringsaveT << endl;


        }
        else if (question == "print")
        {
            cout << "  Please Type the string you want to save." << endl;
            cin.ignore(256, '\n');
            cin >> stringsaveT;
            myfile << "  "<< stringsaveT <<" ";
        }



        myfile.close();
    }

    cout << "Last Cout! program reverts here first? and closes!" << endl;
    return 0;
}

Easy input/output functions:

#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

void open(string filename){
    ifstream f_in (filename.c_str(), ios::in);
    if (!f_in){ 
        cerr<<"Invalid file.\n";
        return;
    }
    else{
        string line;
        while(getline(f_in, line)){
            cout<<line;
        }
    }
}

void save(string filename, string element){
    ofstream f_out(filename.c_str(), ios::out);
    f_out<<element<<'\n';
}

Now, you can put in some delimiters for the getline function from open:
getline(ifstream, string, delimitter) where the delimiter can be any character, but a single character.
If you want to get the whole line, just leave the getline without the delimiter, because getline will try to read either till it reaches EOF or the '\n' character.
If you want to split the input from the file you read, you can use a tokenizer, or a token.

#include <sstream>
void open(string filename){
    ifstream f_in (filename.c_str(), ios::in);
    if (!f_in){ 
        cerr<<"Invalid file.\n";
        return;
    }
    else{
        string line, splitline;
        while(getline(f_in, line)){
            istringstream token(line);
            getline(token, splitline, ',');
            istringstream to_int(splitline);
            int id;
            to_int>>id;
            //that is of course if the first element you read from the text file
            //is of type int, say you have a a.txt file in which the elements are
            //sotred like this: 
            //      1,String line1.
            //      2,String line2.
            //      3,String line3. etc.
            //It will get in the id int, the first number.
            cout<<line;
        }
    }
}

Lucaci Andrew could you please explane your methed more clearly, iwhat your doing is what i could use, i just want to read all the .txt's data. i can figure out the rest from there, but please help me understand your post.

Lucaci Andrew, sorry im kinda a ID10T,(im Jokeing) :)

OH! VernonDozier your methed help's too! thanks! but maybe you can help me with Lucaci Andrew's post, i dont understand some parts.

-_-
(It could also be because of the time im typeing this,9:40PM)

Ok, so which part you don't understand?
I will start with the simple code of reading from file.

void open(string filename){
    ifstream f_in (filename.c_str(), ios::in);

in here you are assigning the ifstream operator to a variable, and you open the file filename. Notice that in order to open a file through a variable of type string, you will need to use the .c_str() part, which returns a C-string from the actual string.
You can easily do it like with a given name, say ifstream f_in ("data.txt", ios::in) but if you're trying to do it via a string, you'll have to convert it to a C-string (adding the '\0' at the end of it). Also, the ios::in flag denotes that you are doing input operation from the file.

if (!f_in){ 
        cerr<<"Invalid file.\n";
        return;
    }

checks if the file is opened, that is, if the file exist and can be opened. If not, it will output that the file is invalid, throughout the cerr (stderr).

This function can easily be replaced with if (!f_in.is_open()) but it's preaty much the same thing.

    else{
        string line;
        while(getline(f_in, line)){
            cout<<line;
        }
    }

coming up the else part of the code, thou it can be removed as from the else condition because if it goes through the if statement it will return from function, but I put it here to evidentiate that this is another part.
So, here I intitialize a string, in which the whole line of the file will be read. Notice that I use the getline method. Getline, as a method, if given only the input stream and a string, it will read from the file till either the '\n' (new line) character appears, or the EOF (end of file).
If you want to store the lines from the file, you can use a stl vector, say like this:
std::vector<string> text_to_be_store in which you simply put the lines.
Going on the second example, that's a little bit more advanced, from the reading perspective. I will use the #include <sstream> library.
If you don't know what that is you can read more from here.
Ok, so in the 2nd example I added something new to the reading function:
1st thing, I added a splitline string, used in holding bits of the line.
This method is usefull (talking about the second example) if you want to split the reading line in parts.

istringstream token(line);

initialized an istringstream (input stringstream) token with the value of line (line, the string in which we have read the entire line).

getline(token, splitline, ',');

again, we're invoking the getline method, with token as the input stream, and splitline as the const string, but we added something different, a delimiter.
The delimiter from the getline method has to be a single character (it's default as I said before is '\n' or EOF). Here we added the ',' (comma) character. I am assuming here that my line of interest is splitted in "sections" by the ','.
Ok, so the splitline string will hold the first part of the string line till it reached the ',' character. Going on, I assumed that the first character of every line is an int, so by

istringstream to_int(splitline);

I created another istringstream variable, denoted to_int with the value of the splitline. The value from the istringstream will than be transfered through the >> operator into the int id.
Than I invoke again the getline method, with the same token as the input stream and with the splitline as the string, which would hold the rest of the string line.

to_int>>id;

So, I hope I made myself understood, and if you need further explanations, say so.

:)
Thanks for the explanation, i will try these out now :)
give me about 20 minutes.
OH! and by the way thanks for the int example you had, ill use that in the future, im just useing string's here, but possabley numbered.

Question,
you said:
ifstream f_in (filename.c_str(), ios::in);
in the first code snippet.
ok... can i have ifstream f_in (filename.c_str(), ios::in); but change it to for example,
ifstream savefile (filename.c_str(), ios::in); ??
i just wonder if i can change ifstream's name to anything, thanks. :)

yes, you can change the name, fin is the name of the ifstream variable which has as attributes the (filename.c_str(), ios::in).
ifstream a, is like string a, or int a, initializing a variable of type ifstring.

0_O
IT WORKS!!!!!!!!!!!!!!!!!!!!!!!!! thanks you guys SO MUCH :)
this is awsome!
Lucaci Andrew you are a life saver! thanks again to Lucaci Andrew and VernonDozier!
thanks you guys!
:)
I encourage you both to see my other post on keyboard input,i'm a ID10T on that subject ,
plus it is crucial for me to learn that subject and know it by heart.
me now knowing how to do this helps me SO much with my future projects, plus my Web sites im constructing.
Once again Thanks you Two!

O_O
Lucaci Andrew ! could you help me ??? its quick.... heres my code.

            if (loopon == "yes" || loopon == "Yes" || loopon == "YES" )
            {
                //BLANK
            }
            if (loopon == "no" || loopon = "No" || loopon == "NO" )
            {
                loopprocess = 0;
                system("cls");
                break;
            }

i added this on to the program, so to have it redo if the user wants. i get a error code at
the first if statment here it is.

        \FILESAVETEST\main.cpp|50|error: no match for 'operator||' in 'std::operator== [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >*)(& loopon))), ((const char*)"no")) || loopon'|

this has got something to do with the || i've got, i have this exact code for another program, and i've got the same #include statments, can you help?
Thanks :)
(OH loopprocess is a int, and loopon is a string)
PS. i really am an ID10T Lucaci Andrew you've been trying to help me this entire time for keyboardinput. wow, ive got no excuse there :)

ok......question heres my code, i cant get to show the server log of a replacat program of the current subject, well heres my code:

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;

int main()
{
     string servlogsave;
     string comand;
     fstream serverlog ("server.log",ios::in);
     if (!serverlog)
     {
         cout << "Serverlog Not found, this could be due to\n the server not created, and there for\n the serverlog does not exist." << endl;
     }
     if (serverlog.is_open())
     {


     while(getline(serverlog,servlogsave))
     {
         cout << "ServerLog's currently being saved, Please wait..." << endl;
         system("cls");
     }
     cout << "Comands: show || shows current server log." << endl;
     getline(cin,comand);
     if (comand == "show")
     {
         cout << servlogsave << endl;
     }
    serverlog.close();
     }
    cout << "Hello world!" << endl;
    return 0;
}

when i type show, it shows nothing....., can you help me? this is probabley a simple ERROR.
thanks :)
i tested and i figured out that after the while loop the string discards its data, ok so should i just move that data to a char or something else?
if i put cout << servlogsave << endl; before the system("cls"); withen the while loop, it
shows the data being saved, weird.

A few tips on how to debug things. You can either use an actual debugger and set breakpoints, which might be something you should consider learning to do, or you can sprinkle some cout statements around the code (remember to delete them later!).

So when I see a line like this...

when i type show, it shows nothing.....

I see the symptom. We need to get from the symptom to the cause. How do we do that? One way is to think, "What are some of the different things that could result in this happening?" A few things pop into my head immediately.

1) Perhaps the command is not registering as "show" for whatever reason.
2) Perhaps nothing is being outputted.
3) Perhaps an empty string is being outputted.

Now how does one narrow these down? Let's look at number 3. How do we make an empty string show up? We surround it with something non-empty. How about exclamation points? How about number 1? Let's stick a debugging statement in there and print it out. How about number 2? Let's stick a debugging statement in the control path that we EXPECT the code should go through. If this debugging statement prints, then we know we were right. If it DOES NOT, we need to look at the code more carefully because our control path is not as expected.

Lather, rinse, and repeat. You keep placing debugging statements in strategic place and you narrow down the problem further and further. Hopefully this provides you clues and eventually a solution. See attached program foran example.

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;

int main()
{
     string servlogsave;
     string comand;
     fstream serverlog ("server.log",ios::in);
     if (!serverlog)
     {
         cout << "Serverlog Not found, this could be due to\n the server not created, and there for\n the serverlog does not exist." << endl;
     }
     if (serverlog.is_open())
     {


     while(getline(serverlog,servlogsave))
     {
         cout << "ServerLog's currently being saved, Please wait..." << endl;
         system("cls");
     }
     cout << "Comands: show || shows current server log." << endl;
     getline(cin,comand);

     cout << "DEBUG1:command=!" << comand << "!" << endl;

     if (comand == "show")
     {
         cout << "DEBUG2:command=!" << comand << "!" << endl;
         cout << "DEBUG3:servlogsave=!" << servlogsave << "!" << endl;
         cout << servlogsave << endl;
     }
    serverlog.close();
     }
    cout << "Hello world!" << endl;
    return 0;
}

Finally, get rid of any system("cls") statements. stick them back in later if you like, but you're debugging so you need to be able to see what's being printed!

Thanks ill test this
:)

ok for when i type in show, i figured out that getline(cin,servlogsave); is the problem,
i fixed it to a simple, cin >> servlogsave, and both DEBUG: cout's show but servlogsave does not show at all. but while i am saveing data to the program it shows me the data being pulled.
weird. could you help, and thanks for the debug tips :)

?
ok ive changed my code....

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
     string permantservlog;
     string servlogsave;
     string comand;
     fstream serverlog ("server.log",ios::in);
     if (!serverlog)
     {
         cout << "Serverlog Not found, this could be due to\n the server not created, and there for\n the serverlog does not exist." << endl;
     }
     if (serverlog.is_open())
     {


     while(getline(serverlog,servlogsave))
     {
         permantservlog = servlogsave;

         cout << servlogsave << endl;
         cout << "\n" << endl;
         system("cls");
         cout << "ServerLOG currently being saved" << endl;
     }
     cout << "Comands: show\t || shows current server log.\n" << endl;
     cin >> comand;
     if (comand == "show")
     {
         cout << " should show up here" << endl;
         cout << "DEBUG:string show!" << permantservlog << "!"  <<endl;
         cout << permantservlog << endl;
     }
    serverlog.close();
     }
    cout << "Hello world!" << endl;
    return 0;
}

but all i get is the last server log, not the full file's worth.

so..... how do i save all the lines/data of the .txt then?

You have lines 21 to 28 that appear to read an entire file one line at a time and display it to the screen. Then, before anyone can every read what you've written, you clear the screen on line 27. What's the point of displaying to the screen if you immediately clear the screen. Then on line 28 you have a comment that says you are "saving". You are not saving anything. This program READS from a file and prints to the screen (again, no one will ever see what's printed due to the system("cls")). So delete line 28. It's an inaccurate description. Delete line 27 so you can see what yoiu have printed. It looks to me like the entire file is printed before you ever get to line 30, and you question is how do you print the entire file. Well, again it looks like you already have, so delete lines 30 - 37 since you have achieved your goal already.

Now as to your question, how do you SAVE all the lines of the file, I suppose you are asking how do you save the contents of one file to another? You open up an output stream at the top of your program and every time you read in a line, you output it to the output stream. So after lines 25, you do this...

outs << servlogsave << endl;

Same thing you have, just replace "cout" with "outs". After line 12, you would open an ofstream called outs.

ofstream outs;
outs.open("outputfile.txt");

At the end, close it just like you did with the input file.

outs.close();

If that's NOT what you are trying to do with all of this, you'll need to word the question more clearly.

ok.... thats kinda what i want, i want to also read all the data from the file and save it to
eather a string or a char.

You can't save an entire file to a char. You can save it to a really big character buffer, but this is C++, might as well use strings. They're easier than character buffers.

thats kinda what i want

You're going to have to be more specific than "kinda". You've posted several contradictory and confusing things in your prior posts about your goal. That's not intended as a criticism, it's just reflecting the fact that you're a newbie and part of being a newbie is that you don't always use the right terms, nor do you always know precisely what you want. Try to decide exactly what the goals of the program are and lay them out as precisely as possible.

ok. my goals are as follows.
1.To achieve the goal of reading all the .txt's data and saveing it to a string
2.To be able to edit the now newly saved .txt data, for example so to add or remove charaters.
3.To be able to understand File Input and output, its working and the most effective ways to get goals 1. and 2. done efficiently and easly.

VernonDozier i will use goals like this for future posts :)

Ok, having the code from your last post, 1st goal:
To save akk the .txt's data into a string.
Not likely possible if you have large amount of data. What you could do is to store them in a container.
Here's your code, saving each line from the server.log into a vector (stl).

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
int main(){
    vector<string> from_file;
    string permantservlog;
    string servlogsave;
    string comand;
    ifstream serverlog ("server.log", ios::in);
    if (!serverlog){
        cout << "server.log Not found, this could be due to\n the server not created, and there for\n the server.log does not exist." << endl;
    }
    if (serverlog.is_open()){
        cout<<"Reading from file.\n";
        while(getline(serverlog,servlogsave)){
            permantservlog = servlogsave;
            from_file.push_back(permantservlog);
        }
    }
    serverlog.close();
    for (;;){
        cout << "Commands: \n"
             << "show\t || shows current server log.\n"
             << "q \t || exits the program.\n";
        cout<<"> ";
        cin >> comand;
        if (comand == "show"){
            for (int i=0;i<(int)from_file.size();i++){
                cout<<from_file[i]<<endl;
            }
            cout<<"\n";
        }
        else if (comand=="q") return (0);
        else cout<<"Invalid command.\n\n";
    }
    return (0);
}

If you want to save to another file, you should add this functions:

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
void saveToFile(string filename, vector<string> list);
int main(){
    vector<string> from_file;
    string permantservlog;
    string servlogsave;
    string comand;
    ifstream serverlog ("server.log", ios::in);
    if (!serverlog){
        cout << "server.log Not found, this could be due to\n the server not created, and there for\n the server.log does not exist." << endl;
    }
    if (serverlog.is_open()){
        cout<<"Reading from file.\n";
        while(getline(serverlog,servlogsave)){
            permantservlog = servlogsave;
            from_file.push_back(permantservlog);
        }
    }
    serverlog.close();
    for (;;){
        cout << "Commands: \n"
             << "show\t || shows current server log.\n"
             << "save\t || saves to a given filename.\n"
             << "q \t || exits the program.\n";
        cout<<"> ";
        cin >> comand;
        if (comand == "show"){
            for (int i=0;i<(int)from_file.size();i++){
                cout<<from_file[i]<<endl;
            }
            cout<<"\n";
        }
        else if (comand=="q") return (0);
        else if (comand=="save"){
            cout<<"Filename: ";
            string filename;
            cin>>filename;
            saveToFile(filename, from_file);
        }
        else cout<<"Invalid command.\n\n";
    }
    return (0);
}

bool check(string filename){
    ifstream in(filename.c_str());
    return (in.good());
}

void saveToFile(string filename, vector<string> list){
    if (check(filename)){
        cout<<"File already exists.\n";
        return;
    }
    ofstream to_file(filename.c_str(), ios::out);
    for (int i=0;i<(int)list.size();i++){
        to_file<<list[i]<<'\n';
        cout<<list[i]<<endl;
    }
    cout<<"Done writing to file: "<<filename<<endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.