Archived

This topic is now archived and is closed to further replies.

XDarkScar

fstream reading

Recommended Posts

#include <iostream>
#include <fstream>
using namespace std;
int num;

int main()
{
	cout << "Enter the file number\n";
	cin >> num;

	ifstream fin;
	fin.open("???");

	the rest of the fstream code...
	return 0;
}
 
How would you read the file thay tipe in? user 1 load 1.txt user 999 load 999.txt how? Easy way of programming: Code, Graphics, Swearing....

Share this post


Link to post
Share on other sites
int main()
{
cout << “Enter name of file to be opened: “;

string filename;
cin >> filename;

// open file for input
ifstream infile(filename.c_str());

if (!infile)
{
cerr << “Unable to open file: “
cout << filename << “Quitting\n”;
return -1;
}

char ch;
while (infile.get(ch))
cout.put(ch);//or store into a buffer

return 0;


[edited by - code_conspiracy on May 5, 2003 3:10:22 AM]

Share this post


Link to post
Share on other sites

  
#include <iostream>

#include <fstream>


#include <string>

using namespace std;
int num;

int main()
{
cout << "Enter the file number\n";
cin >> num;
ifstream fin;

// string to store name

char buffer[32];

// Set all characters to 0 in array.

memset( buffer, 0, 32 );

// Make number into string and store in buffer

itoa( num, buffer, 10 );

// Add ".txt" to the end of buffer

strcat( buffer, ".txt" )

// Open file

fin.open( buffer );


// the rest of the fstream code...



return 0;

}



:::: [ Triple Buffer V2.0 ] ::::

Share this post


Link to post
Share on other sites
Or you could use a string stream:


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

int main()
{
    std::cout << "Enter the file number\n";
    int num;
    std::cin >> num;

    std::ostringstream oss;
    oss << num << ".txt";     // converts the int and the .txt extension into a string representation

    std::ifstream fin( oss.str().c_str() );

    // here, str() returns the string representation (std::string) and then c_str() converts it to a char*
    // (because std::ifstream's constructor takes a char* argument, not a std::string argument)

    ... stuff ... "the rest of the fstream code"

    fin.close();

    return 0;
}



[ Google || Start Here || ACCU || MSDN || STL || GameCoding || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on May 5, 2003 6:29:09 AM]

Share this post


Link to post
Share on other sites