开发者

text from a file turned into a variable?

开发者 https://www.devze.com 2022-12-29 04:02 出处:网络
If I made a program that stores strings on a text file using the \"list\"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to

If I made a program that stores strings on a text file using the "list"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to type in all of the text I copied somewhere by using that one variable to refer to the text), do I use a string,double,int o开发者_JAVA百科r what do I declare that chunk of text as?

I'm making the program using c++ in a simple console application.

Easier explanation for PoweRoy:

I have a text in a .txt file,I want to copy everything in it and then all this that I just copied, I want to call it "int text" or "string text" or whatever.But I don't know which one of those "int","string","double" etc. to use.


To take some pity on you, this is about the simplest C++ program that reads a file into memory and then does something with it:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

int main() {

    ifstream  input( "foo.txt" );
    if ( ! input.is_open() ) {
        cerr << "could not open input file" << endl;
        return 1;
    }

    vector <string> lines;
    string line;
    while( getline( input, line ) ) {
        lines.push_back( line );
    }

    for ( unsigned int i = 0; i < lines.size(); i++ ) {
        cout << (i+1) << ": " << lines[i] << "\n"; 
    }
}


Broadly speaking, you are talking about the concept of Serialization - storing variable values in permanent storage like a file so you can reload them later. Have a look at that link to broaden your understanding.

Specifically, it sounds like you have arbitrary text in a file and want to refer to it in your program. In that case, string sounds appropriate. Unless the text in the file is intended to represent one single number, that seems most appropriate.

Note that if you have structured data (like a CSV file or XML file), a more complex data structure (e.g. a class, array of classes, etc) might be a better choice.


#include <iostream>
#include <fstream>
#include <string>

int main() {
   // Open stream from file
   std::ifstream ifs("foo.txt");

   // Get file contents
   std::string file_contents(
      (std::istreambuf_iterator<char>(ifs)),
      std::istreambuf_iterator<char>()
   );

   // Output string to terminal to see that it works
   std::cout << file_contents;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消