Sunday, May 10, 2009

C++: fstream user input ?????? NEED HELP!?

Hello,





I'm trying to write a C++ program which uses input from a file. However, I want to prompt the user to choose which file they want to use as input. I have an input.txt which contains some data ( 5 integers ) and I want the user to be able to select that file for input in the program. This is where my problem arises, getting the user to choose. I've compiled the program but it doesn't work right. Here is the code:





//program to practise file input from a user





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


using namespace std;








struct data{





int first, second, third, fourth, fifth;


};











int main()


{


data name;


double file;





cout %26lt;%26lt; "Please input the name of the .txt file that you would like to open: " %26lt;%26lt; endl;


cin %26gt;%26gt; file;





ifstream infile("file.txt");








infile %26gt;%26gt; name.first %26gt;%26gt; name.second %26gt;%26gt; name.third %26gt;%26gt; name.fourth %26gt;%26gt; name.fifth;





cout %26lt;%26lt; name.first %26lt;%26lt; name.second %26lt;%26lt; name.third %26lt;%26lt; name.fourth %26lt;%26lt; name.fifth %26lt;%26lt; endl;





return 0;





}

C++: fstream user input ?????? NEED HELP!?
Your code is just awful.





%26gt;double file;


First of all, of you are inputing a file name, won't that be a string or a collection of characters. Double will contain numeric values. Invalid type exception.





%26gt;ifstream infile("file.txt");


if you are already asking for input from the user, why are you specifying a file name called "fie.txt". WRONG!





Well since you cant get it right, I'll as well give you the code. Since most of the errors are not too big, might be for you (*snikers*). Alrighty, maybe this will give you an idea.





#include%26lt;iostream%26gt;


#include%26lt;fstream%26gt;


using namespace std;





struct data


{


int First, Second, Third, Forth, Fifth;


};





int main()


{


data name;


char fileName[10];





cout %26lt;%26lt; "Please input the name of the .txt file that you would like to open: " %26lt;%26lt; endl;





if(cin %26gt;%26gt; fileName)


{


ifstream infile(fileName);


infile%26gt;%26gt;name.First%26gt;%26gt;name.Second%26gt;%26gt;nam...





cout%26lt;%26lt;name.First%26lt;%26lt;name.Second%26lt;%26lt;name....


}





return 0;


}





Make sure that the input be the correct file name, like "input.txt" and the inut file should have the integers followed by a white charater, like space. Example:


1 2 3 4 5 6





otherwise you'll end up with more errors.
Reply:If statement is nothing but an error checking statement. It'll protect your rest of the block i.e. in infile(), cause you can know that the actual error is just the bad input not your code. ^^ Report It



No comments:

Post a Comment