Question:
How to get input from a text file in c++?
Adeep
2014-05-01 13:45:07 UTC
i need to get input from a .txt file. but i'm having a problem. i can't seem to get the program to take the values inside the text file as input, it is seting each input as 0. below is the the code i wrote. the rest of the algorithm of the test i manage to code it. only input i have problem. anyone familiar with randomness test? or monobit test? can please help me? the idea here is:
lets say the size of the input is 100bits. so the user will set the value of "n" which is 100. than the program will access the text file to get the input and manipulate it before storing into an array.

#include
#include
#include
using namespace std;
int main ()
{
// declaring variables:

int j=0,n,a;
double Sobs, prob;
int sum = 0;
cout<<"please input frequency (n) (length of bit string) = " < cin>> n;
int numbers[n];



for (int i = 0; i {

ifstream myfile;
myfile.open ("data.txt");
myfile >> a;
j = a*2-1;
numbers[i]=j;
myfile.close();

}
cout<<"\nthe numbers inside the array are : \n\n";
for (int i=0; i {
cout<<(numbers[i]);

}
Three answers:
?
2014-05-01 21:44:44 UTC
The answer is quite simple... Every single time your for loop increments it opens the file grabs the first value then closes the file. The first value is 0, therefore you get all zeros.



to fix it take the file code outside the loop:

ifstream myfile;

myfile.open ("data.txt");

for (int i = 0; i
{

myfile >> a;

j = a*2-1;

numbers[i]=j;

}

myfile.close();
2014-05-06 05:24:35 UTC
Jeff answered 4 days ago

The answer is quite simple... Every single time your for loop increments it opens the file grabs the first value then closes the file. The first value is 0, therefore you get all zeros
Am0s
2014-05-01 14:14:50 UTC
Learning C, C# and C++ is best when you have someone, in person, that you can ask these kinds of questions, and give suggestions, quickly, and move on to the next learning lesson.



First, how do you know your file is at least the size the user specifies, that you don't try to read past the end of the file? You may also want to use a function to read from the stream.



Suggested reading:

http://www.cplusplus.com/forum/beginner/32690/

http://www.cplusplus.com/reference/istream/istream/get/



http://stackoverflow.com/questions/12240010/how-to-read-from-a-text-file-character-by-character-in-c



you might want to add these sites to your regular reading list....



for more ideas: google the search term "c++ read file char by char"


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...