Hi Guys! Just wondering, is it possible to read a number from a txt file? If so how? I have been trying for a while and cant seem to figure it out. Any help would be greatly appreciated.
Printable View
Hi Guys! Just wondering, is it possible to read a number from a txt file? If so how? I have been trying for a while and cant seem to figure it out. Any help would be greatly appreciated.
>is it possible to read a number from a txt file?
Yes, and C++ makes it very easy. Once you open a file stream, you can use it just like cin:
Code:#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int number;
ifstream fin("file.txt");
// Always check for failure
if (!fin) {
cerr<<"Error opening file\n";
return EXIT_FAILURE;
}
// Likewise, any input should be checked
if (!(fin>> number)) {
cerr<<"Input error\n";
return EXIT_FAILURE;
}
cout<<"The number read was "<< number <<endl;
return EXIT_SUCCESS;
}
ive been trying to do the same thing but that only would work for the first number in the file it wouldnt work if you hadsay 50 numbers in the file.
how would you do that?
ive read the tutorial and i still didnt se how you would choose one number outta 50 in one already created text file
Hm... how about a loop?
Quzah.
I think what your looking for is something like this:
*edit*Code:#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int x = 0;
int number[10];
ifstream myFile;
myFile.open("File.txt"); //open file
if(!(myFile.is_open())) { //ensure file opened
cout <<"Error opening file";
return 0;
}
while(!(myFile >> number[x] == NULL) && (x < 10)) { //check for EOF and ensure do not overrun array
x++;
}
for(int i =0; i < 10; i++) {
cout << number[i] << endl; //print result
}
return 0;
}
Now if you do not know how much you are inputting you could eihter dynamically reallocate the array or just use the vector class(easiest approach).
*end edit*
Happy Coding!!
Oops! My bad, thanks for pointing that out. I updated my code so it doesn't show that bad, terrible bug causing thing anymore. ;)
-Andy
Just made a few improvements on yours andy.
Code:#include <iostream>
#include <fstream>
int main(void)
{
int i = 0, j;
int number[10];
std::ifstream myFile;
myFile.open("file.txt");
if(!myFile)//file doesn't exist or some other reason for it failing
{
std::cout<<"Could Not Open file.txt"<<std::endl;
std::cin.get();
return 0;
}
while(myFile>>number[i] && i < 10)//input numbers in our file only up to 10 numbers
{
i++;
}
for(j = 0; j < i; j++)//only printing the numbers that we read in
{
std::cout<<number[j]<<std::endl;
}
std::cin.get();
return 0;
}
nice, I see you are a fan of the C99 standard too:
[edit]Quote:
int main(void)
How about this -
Now of course in reality you would resize in chunks, but this is just an example.Code:#include <iostream>
#include <fstream>
#include <stdlib.h>
int main(void){
int x=0, arraySize=0;
int* number = NULL;
std::ifstream myFile;
myFile.open("File.txt"); //open file
if(!myFile) { //ensure file opened
std::cout <<"Error opening file";
std::cin.get();
return 0;
}
while(!((myFile >> x)==NULL)) { //check for EOF
if(!(number = (int*)realloc(number, (arraySize+1) * sizeof(int)))){ //resize array by one int
std::cout << "Error allocating array" << std::endl;
std::cin.get();
return 1;
}
number[arraySize++] = x;
}
for(int i =0; i < arraySize; i++) {
std::cout << number[i] << std::endl; //print result
}
std::cin.get();
return 0;
}
-Andy
[/edit]
:)Code:#include <iostream>
#include <fstream>
#include <vector>
int main(void)
{
int x = 0, arraySize = 0, i = 0;
std::vector<int> number;
std::ifstream myFile;
myFile.open("file.txt",std::ios::in);
if(!myFile)//file doesn't exist or some other reason for it failing
{
std::cout<<"Could Not Open file.txt"<<std::endl;
std::cin.get();
return 0;
}
while(myFile>>x)//input numbers in our file only up to 10 numbers
{
number.push_back(x);
arraySize++;
}
for(i = 0; i < arraySize; i++)//only printing the numbers that we read in
{
std::cout<<number[i]<<std::endl;
}
std::cin.get();
return 0;
}
i dont think you guys understand what im saying. I am using this to save and load characters in a text (console) adventure. I create the table to a txt file and i can get it to display but i cant get the loaded characters stats to apply to the ones in the txt file.
you guys are showing me how to show all of them in the 50 numbers or characters i need to move the curser to a specific position and load from there.
If you are dealing with the file while your program is running the best thing to do is to load the file into a memory structure such as a vector and manipulate it from there. Once your program is completely done with the information save the vector back into the file. The following is an example of loading a file into a vector and then only displaying the 3rd through the 5th numbers.
Happy Coding!!Code:#include <iostream>
#include <fstream>
#include <vector>
int loadFile(std::vector<int>*, const char*);
int main(void) {
std::vector<int> vFile; //create vector to hold file information
std::vector<int>::iterator iFile; // create iterator to move through vector
int offset = 0;
if((loadFile(&vFile, "FileDemo.txt")) == 1) { //load our file into the vector and check for an error
std::cout << "Error Loading File" << std::endl;
std::cin.get();
return 1;
}
std::cout << "Printing from the file starting a the 3rd number and going to the 5 number" << std::endl;
offset = 2;
for(iFile = (vFile.begin() + offset); iFile < (vFile.begin() + 5); iFile++) { //move through the vector
std::cout << *iFile << std::endl;
}
std::cin.get();
return 0;
}
int loadFile(std::vector<int>* my_vector, const char * szfileName) {
std::ifstream myFile;
int myNumber = 0;
myFile.open(szfileName, std::ios::in);//Load the file
if(myFile == NULL) //check for error
return 1;
while(!((myFile >> myNumber)==NULL)) { //check for EOF
my_vector->push_back(myNumber); // load contents of file into vector
}
myFile.close();
return 0;
}
Holy Deja-Vu, Batman!
Let's spell this out very slowly: If some one makes a post such as the origional posters, and then hasn't checked back in over 10 posts, they probably don't really want to learn anything. They want the whole thing done for them. And guess what? There are a bunch of suckers posting here who're just jumping at the chance to do it. Thank you for contributing to the never-ending flow of this type of post.
Quzah.
quzah dejavu to you too
all you do is complain about people i can honestly say ive looked at everything you shown me so far and i dont get it and so i post ive tried coding didnt get how so i post
how the hell can i code something then post if i dont know how
The problem here is, he says he has tried and so on but he doesnt show us what he tried. for all I know it could be a Hello World app he has tried with.
well ive used them in actual apps and i know what im talking about for the most part. maybe im just in bad posts but quzah always is like that
Go look it up. You apparently have no idea what the term means.Quote:
Originally Posted by GamingMarvel
Yeah and I've looked at everything you've shown me so far, which is exactly jack I am sillyI am sillyI am sillyI am silly. Go read the forum rules. If you're stuck on code, post your attempt. We're not here to do everything for you.Quote:
Originally Posted by GamingMarvel
No, wait, it gets better:
So you've "used them in actual apps" and... "i know what im talking about for the most part", but some how we get: "how the hell can i code something then post if i dont know how"Quote:
Originally Posted by GamingMarvel
Make up your mind. Which is it? You do or you don't know how?
Quzah.
okay let me specify myself. I have the basic idea of the things you are suggesting and i thank you for it. But i'm also saying that i've tried the code you gave me or another user has. and it works but not for what i need. From there on I'm confused on how to change it to work. I gave you something specific to go by and I don't see the point in reposting correct code. I'm also sorry if I've turned this post into a war zone that's not what i intended at all. I apologize I'm just a little frustrated because I'm tryin to do something that sounds really simple but i can't either understand or no one else seems to know understand or can provide the code and give me the required understanding.
Oh and after words i realized i screwed up when i used the word Dejavu. Yes I know what it means. It's like reliving something that you have or thought you have lived once. It's French.
This isn't C99, this is C++, I thought it was customary to NOT put void in the main:
Quote:
Originally Posted by prog-bman
It doesnt matter
I believe using empty parenthese is the same as saying that no arguments should be taken.Code:int main(void) == int main() // in C++
Correct me if im wrong.
Yeah but progman was correcting somebody else's code, and I believe sticking a void in there isn't doing anything! And I believe that we all should agree on int main():
http://faq.cprogramming.com/cgi-bin/...&id=1043284376
For no args in C++
The standard
Quote:
Change: In C + +, a function declared with an empty parameter list takes no arguments.
In C, an empty parameter list means that the number and type of the function arguments are unknown"
Example:
int f(); // means int f(void) in C + +
// int f(unknown) in C
Rationale: This is to avoid erroneous function calls (i.e. function calls with the wrong number or type of
arguments).
Effect on original feature: Change to semantics of welldefined
feature. This feature was marked as
“obsolescent” in C.
Difficulty of converting: Syntactic transformation. The function declarations using C incomplete declaration
style must be completed to become full prototype declarations. A program may need to be updated
further if different calls to the same (nonprototype)
function have different numbers of arguments or if the
type of corresponding arguments
Yes exactly, for C programming we go like this:
But the all-new C++ way is:Code:int f(void);
So that's why I believe we should just use:Code:int f();
for C++ programs, instead of being consistent! omg I don't know why I started this arguement, I'm an idiot!! *cries* IT DOESN'T EVEN MATTERCode:int main()
|
|
|
v
I was just saying my method is ok. Its all a style thing like alot of stuff :)
>I believe using empty parenthese is the same as saying that no arguments should be taken.
Correct. C++ supports the C method of using void to specify no arguments. Also, in the case of main (which is rarely declared anymore, only defined), the following definitions are identical in both C and C++:
Though for consistency, the former is preferred in C++ for all declarations and definitons, and the latter is preferred in C. Following that guideline keeps things consistent in both languages and protects against problems concerning K&R style function declarations in C.Code:int main()
int main(void)
though i have problems with files and streaming, i managed to write this code. but that only reads numbers if there are ONLY numbers in a file. Well, the data in my text file represents kind of a MxM table of numbers which are divided by comma.Quote:
Originally Posted by prog-bman
I believe that i only need one more >> NONnumberCHAR after the while(myFile>>number[j]...).
So it would look something like this:
Code:int array[30];
char NONnumberCHAR[];
while ((myFile>> number >> NONnumberCHAR) && (j < 30))
{
array[j] = number;
j++;
}
i got it! and it almost works fine!
content of my file:
Code:-1,55,25,45,-1,-1,-1,-1
55,-1,-1,-1,5,-1,-1,-1
25,-1,-1,-1,40,-1,-1,-1
45,-1,-1,-1,20,-1,-1,30
-1,5,40,20,-1,35,15,-1
-1,-1,-1,-1,35,-1,10,-1
-1,-1,-1,-1,15,10,-1,50
-1,-1,-1,30,-1,-1,50,-1
as i said, it almost works fine. this is what I get:Code:while (!Graph.eof()) {
Graph>> Matrika[j][i]; // Matrika = matrice in which the numbers from the file are saved
Graph>> buu; // the comma character is read into buu
i++; // for every read, i is increased (i represents columns)
if (i == (m)) { // NOTE: m represents the size of the matrice, so when i is equal to m then we need to jump into next row and put i back to zero to begin writing in the first column of the next row
i = 0;
j++;
}
}
NOTE: first character from every line but the first is missing. why,i have no clue? anyone?Code:-1 55 25 45 -1 -1 -1 -1
5 -1 -1 -1 5 -1 -1 -1
5 -1 -1 -1 40 -1 -1 -1
5 -1 -1 -1 20 -1 -1 30
1 5 40 20 -1 35 15 -1
1 -1 -1 -1 35 -1 10 -1
1 -1 -1 -1 15 10 -1 50
1 -1 -1 30 -1 -1 50 -1
>NOTE: first character from every line but the first is missing. why,i have no clue? anyone?
> Graph>> buu; // the comma character is read into buu
So you skip commas, but guess what. There's no comma at the end of a line.
Graph>> Matrika[j][i]; // Matrika = matrice in which the numbers from the file are saved
should skip commas automatically, so you should be able to remove that Graph>>buu; line.
Nope. Look at the other posts in this thread, and even your own example that you posted first.Code:while (!Graph.eof())
Doesn't work for me:Quote:
Graph>> Matrika[j][i]; // Matrika = matrice in which the numbers from the file are saved
should skip commas automatically, so you should be able to remove that Graph>>buu; line.
Code:#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile("C:\\TestData\\data.txt");
/* data.txt:
-1,55,25,45,-1,-1,-1,-1
*/
int num[10] = {0};
inFile>>num[0];
cout<<num[0]<<endl; //-1
inFile>>num[1];
cout<<num[1]<<endl; //0 ???
return 0;
}
>Doesn't work for me:
7stud, yes you're right.
I guess a few options are:
(1) If it was easy enough, reformat the file, replacing the commas with spaces.
(2) Add a comma to the end of each line in the file.
(3) Use C style I/O to read the file.
(4) Read the file a line at a time, and parse.
thanks swoopy! now it works fine!
here is the final code. it's altered a bit.
EDIT: i just now saw that there are more posts on the next page. well,i guess i don't have to change anything because it is working perfectly. i have already tested it with numerous matrices and no errors occur. Oh,and the numbers HAVE to be separated with commas. Thanks again!Code:int stev;
while (!Graf.eof()) {
Graf>> stev; // reads numbers
if (stev == -1) Matrika[j][i] = 10000; // if a value in the file is -1 (which means there is no link with another node) then write 10k into the matrix
else Matrika[j][i] = stev; //else just put the number in the matrix
i++;
if (i < m) {
Graf>> buu; //if it's not at the end of the line,read commas
}
else {
i = 0; // else just skip to next line!
j++;
}
}
...still wrong. Reaching eof causes an error flag to be set in the stream, which terminates the loop. However, other things can cause an error flag to be set in the stream before eof is encountered. If an error flag gets set in the stream before eof is encountered, no further values can be read from the stream. That means eof will never be reached, and consequently your while loop will never terminate--causing an infinite loop.Code:while (!Graf.eof())
i don't understand. in which occurence can an error flag be expected?Quote:
Originally Posted by 7stud
i ran the program with three different files,and each produced a correct minimum spanning tree with prim's algorithm.i helped myself with debug and no errors occured. how else can i check whether i have errors in my program?
>i don't understand. in which occurence can an error flag be expected?
just put
as your loop condition.Code:Graf >> stev
hello!after more than an hour of fcuking with dynamic arrays i did what you said, and it worked fine. and all this time i thought my compiler has gone nuts,by not understanding the basic initialisation of 2D matrix. :mad:Quote:
Originally Posted by dra
well,thank you very much!!!!