How to read integer value from file in C++ - c++

How can read integer value from file? For example, these value present in a file:
5 6 7
If I open the file using fstream then how I can get integer value?
How can read that number and avoid blank space?

ifstream file;
file.open("text.txt");
int i;
while (file >> i) {
cout << i << endl;
}

ifstream f(filename);
int x, y, z;
f >> x >> y >> z;

ifstream f;
f.open("text.txt");
if (!f.is_open())
return;
std::vector<int> numbers;
int i;
while (f >> i) {
numbers.push_back(i);
}

It's really rare that anyone reads a file Byte by Byte ! ( one char has the size of one Byte).
One of the reason is that I/O operation are slowest. So do your IO once (reading or writing on/to the disk), then parse your data in memory as often and fastly as you want.
ifstream inoutfile;
inoutfile.open(filename)
std::string strFileContent;
if(inoutfile)
{
inoutfile >> strFileContent; // only one I/O
}
std::cout << strFileContent; // this is also one I/O
and if you want to parse strFileContent you can access it as an array of chars this ways: strFileContent.c_str()

Related

How to use file.eof() while reading in integers from a file?

I am writing a program that reads in data from a file. The file contains lines of integers, such as
5 6 2 8 6 7
2 5 3
4 0 9 1 3
The first integer of each line corresponds to how many numbers there are in that line. My goal is to read in each line, store the numbers in a vector, and do some operation on them. Here is what I have done:
int main(){
vector<int> vec;
int amount;
int nums;
ifstream file ("file.txt");
while(!(file.eof())){
file >> amount;
cout << amount << endl;
for (int i = 0; i < amount; i++){
file >> nums;
vec.push_back(nums);
}
printArray(vec);
bubbleSort(vec);
vec.clear();
}
return 0;
}
Unfortunately, the last line always gets read twice. I looked online and saw that the eof() function should not be used to maintain loops. What else could I use in this situation?
Thanks.
operator>> sets the stream's eofbit flag if it tries to read past EOF. You can use that condition to break your loops. But you have to actually perform a read operation BEFORE you can evaluate eof(). See Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong? for more details on that.
Since you are dealing with line-based text, you can use std::getline() to read each line first, and then you can use std::istringstream to parse each line, eg:
int main()
{
vector<int> vec;
ifstream file ("file.txt");
string line;
while (getline(file, line)) {
istringstream iss(line);
int amount, nums;
iss >> amount;
cout << amount << endl;
for (int i = 0; (i < amount) && (iss >> nums); ++i){
vec.push_back(nums);
}
printArray(vec);
bubbleSort(vec);
vec.clear();
}
return 0;
}
Alternatively, you can simply take advantage of the fact that operator>> skips whitespace, including line breaks, eg:
int main()
{
vector<int> vec;
int amount, nums;
ifstream file ("file.txt");
while (file >> amount) {
cout << amount << endl;
for (int i = 0; (i < amount) && (file >> nums); ++i){
vec.push_back(nums);
}
printArray(vec);
bubbleSort(vec);
vec.clear();
}
return 0;
}
Although, this approach would be a little less resilient to errors in the input data, compared to the std:getline() approach. If the actual amount of numbers in a given line does not match the specified amount at the beginning of the line, this approach will get its reading of the file out of sync. Worse, if a given line contains any non-integer values, this approach will fail to read any subsequent data at all.
In the std:getline() approach, if a given line is malformed, the code will simply move on to the next line and continue on like nothing bad happened.

Perform calculation seperately on values from file in C++ [duplicate]

This question already has answers here:
Read file line by line using ifstream in C++
(8 answers)
Closed 3 years ago.
So I have a input file which contains several different integer values(each in a seperate line), now I need to read each value, find the square root and get the output. The issue I am having is that my code only reads the first value from the input file. I have a feeling I am supposed to be using a loop to read each value seperately, so if someone can help me out it would be really appreciated.
float file_inp() //reads values from file and calculates the square root
{
float y = 0;
ifstream fin;
fin.open("input.txt",ios::in);
if (fin)
{
int x = 0;
fin >> x;
y=sqrt(x);
}
return y;
}
int main()
{
float y = 0;
cout << file_inp();
system("Pause");
return 0;
}
The main problem is that you have a function that reads the file and returns one number.
No amount of looping can make that function produce more than one number.
Instead of one function that does all the work, it's often better to have functions that do a little bit of work and use them over and over.
It's also a good idea to separate I/O from data processing.
This the common "elementwise processing of whitespace-separated input" loop:
int main()
{
std::ifstream input("input.txt"); // No 'ios::in'; it's already an input stream.
SomeType piece;
while (input >> piece) // Read until you can't read no more.
{
process(piece); // Do whatever you want to do.
}
}
Adjust types and processing as necessary.
In your case,
int main()
{
std::ifstream input("input.txt");
int x;
while (input >> x)
{
std::cout << std::sqrt(x) << std::endl;
}
}

Reading in from a CSV data file, erroring out when trying to pull in only what I need

I am trying to pull two columns of data from a CSV file and dump the rest.
The errors I am receiving are:
C2296: '>>': illegal, left operand has type 'std::basic_istream> &(__thiscall std::basic_istream>::* )(_Elem *,std::streamsize)'
C3867: 'std::basic_istream>::read': non-standard syntax; use '&' to create a pointer to member
The data is formatted as such:
1928,44.50%,.......
I want the 1928 assigned into data.year, and the 44.50% assigned into data.yield, but not including the percent sign.
bool ReadData(MyData &data)
{
//Variable for reading data into file stream
ifstream inFile;
string trash;
char junk;
cout << "\nReading file . . .";
//Open data file
inFile.open("Data.csv");
//Read the first 18 lines, and throw it away
for (int i = 0; i < 18; ++i)
{
getline(inFile, trash);
}
//Read the necessary data into the arrays
for (int i = 0; i < SIZE; ++i)
{
//===============================================================
//This line is throwing 2 errors
//Goal: read first column of a simple integer into data.year, discard the comma, then read the second column of a double into data.yield, discard the percentage sign. infile.ignore(); to clear cin stream, getline(inFile, trash) to discard remainder of the lines.
inFile.read >> data.year[i] >> junk >> data.yield[i] >> junk >> trash >> endl;
//===============================================================
inFile.ignore();
getline(inFile, trash);
}
//Return false if file could not be opened
if (!inFile)
{
cout << "\n\nTechnical error! The file could not be read.";
return false;
}
else
{
cout << "\n\nFile opened successfully!";
return true;
}
inFile.close();
}
struct MyData
{
int year[SIZE];
int yield[SIZE];
double minYield;
double maxYield;
double avgYield;
};
Where am I going wrong?
The very first problem is reading a file line by line constant number of times, however you never know the size of the file. So, you should add another check to your for loop. The second problem is that you say the yield is an int but it is a double in the file. The third problem is reading formatted data is not something like you did. The following piece of code can work for you, or you can play a bit with the code.
for (int i = 0; i < SIZE && std::getline(infile, line); ++i) {
std::stringstream linestream(line);
std::string year, yield;
getline(linestream,year,',');
getline(linestream,yield,',');
yield.erase(std::remove(yield.begin(), yield.end(), '%'), yield.end()); // remove %
myData.year[i] = std::stoi( year ); // string to int
myData.yield[i] = std::stod( year ); // string to double
}
PS: Don't forget to include sstream library.
inFile.read >> data.year[i] >> junk >> data.yield[i] >> junk >> trash >> endl;
inFile.read is a function and has no operator >>, that's why you get the error. See https://en.cppreference.com/w/cpp/io/basic_istream/read
I'd suggest you try a different approach: Read the entire line and use a explode function to retrieve the individual elements. For example Is there an equivalent in C++ of PHP's explode() function?

Convert a character to an integer in C++ language

I want to convert from char to integer,
following is the code-
FILE *p;
char temp;
int temp_int;
p=fopen("week3data","r");
temp=getc(p);
temp_int=atoi(temp)
number in file goes from 1 to 200, need some guidance.
If you're using C++, please use C++ SL:
std::fstream stream("file.txt", std::ios_base::in);
float number;
stream >> number;
std::cout << number;
Edit: Don't forget to check if your stream is valid:
if (!stream) {
throw std::runtime_error("Cannot open file");
}
If you're reading from a file, you shouldnt be using
temp=getc(p);
and if you use
temp=fgetc(p);
and the number is, for example 200, you will only read the "2".
so the answer is:
better use
char * buffer;
fgets(buffer,10, p);
temp_int=atoi(buffer);

Want to read line by line but fstream read only first line

A very simple program: read a file line by line (each line contains integer) then do something and write the output to a file.
int main()
{
ifstream fin ("f:\in.txt");
ofstream fout ("f:\out.txt");
int a;
while (fin >> a) {
int b = (a >> 6) & 255;
fout << b << endl;
}
return 0;
}
The input as multiple lines like this:
93859312
2635577168
2929619024
312396812
3019231016
3139200356
...
But the while loops is iterated only one time!! and output only contains
183
Which corresponds to the first input line. Why???
The numbers after the first one are larger than an int can represent.
Instead of int a;, use long long int a;
The largest value than an int can represent is 2,147,483,647:
What is the maximum value for an int32?
Your first value is less than this, but your second is not.
Thus (fin >> a) fails (i.e. is not true), and your program exits from the while loop.