Read Numeric Data from a Text File in C++
Repeat >> reads in loop.
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
Result:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
If you know exactly, how many elements there are in a file, you can chain >> operator:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
Edit: In response to your comments in main question.
You have two options.
- You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
- You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.
Edit: How to skip values in file
To choose the 1234th value, use the following code:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
C Reading Numbers From Text File
You need to seek to the beginning of the file after counting all the commas. You're at the end of the file when you start the fscanf()
loop, so they're all failing and you're not reading anything.
The loop that reads the numbers should only run counter
times. res
is the number of bytes in the file, which is at least twice as many numbers. There's no point in using res
.
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *file;
file = fopen("example_input.txt","r");
int m;
int counter = 0;
while((m = fgetc(file)) != EOF) {
if (m == ',') {
counter++;
}
}
counter++; // 1 more for the last number
int n[counter] = {0};
fseek(file, 0L, SEEK_SET);
for (int i = 0; i < counter; i++) {
if (fscanf(file, "%d,", &n[i]) != 1) {
break;
}
}
for (int a = 0; a < counter; a++) {
printf("%d ", n[a]);
}
}
Reading numbers from a text file into an array in C
change to
fscanf(myFile, "%1d", &numberArray[i]);
Reading multiple numbers from a text file in C
It's better if you don't use a loop with a hardcoded number limit. In my solution I read the numbers until there aren't any numbers left. You'll also not want to use a return
statement inside your loop as that will exit the current function.
#include <stdio.h>
#include <limits.h>
int main()
{
int smallest = INT_MAX;
int second_smallest = INT_MAX;
int number;
FILE *infile = fopen("numbers.txt", "r");
if (infile)
{
while (fscanf(infile, "%d", &number) == 1)
{
if (number < smallest)
{
second_smallest = smallest;
smallest = number;
}
else if (number < second_smallest)
{
second_smallest = number;
}
}
fclose(infile);
}
printf("smallest: %d\n", smallest);
printf("second smallest: %d\n", second_smallest);
return 0;
}
Reading integer to a text file in C (integer is present in a structure)
I guess you are trying to read the file using a text editor.
Issue is with fwrite:
"fwrite" will write the numbers without converting it to ASCII or utf-8 chars hence numbers won't be found when opened via file editor. Instead, you will find a characters equivalent of the numbers stored. Try reading the file using "fread" you will get the actual values back into the "employee_details" structure.
Incase you want to read the data via file editor: use fprint
Try something Like:
fprintf(p_wfile , "%s %d\n", employee.name, employee.id);
How to read a number from a file and use it as a variable in C++?
Hope this piece of code will help.
#include <bits/stdc++.h>
using namespace std; //change headers and namespaces; included for ease of use;
vector<string> split(const string &text, const char sep) {
vector<string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) not_eq string::npos) {
tokens.emplace_back(text.substr(start, end - start));
start = end + 1;
}
tokens.emplace_back(text.substr(start));
return tokens;
}
int main()
{
ofstream outdata;
outdata.open("example.txt");
if( not outdata ) {
cerr << "Error: file could not be opened" << endl;
exit(1);
}
outdata<<"CharacterName1"<<','<<10.0<<','<<40.0<<endl; //writing data into file
outdata<<"CharacterName2"<<','<<20.0<<','<<30.0<<endl;
outdata<<"CharacterName3"<<','<<30.0<<','<<20.0<<endl;
outdata<<"CharacterName4"<<','<<40.0<<','<<10.0<<endl;
outdata.close();
ifstream inputFile;
inputFile.open("example.txt",fstream::in);
if (inputFile.fail())
{
cerr<<"Error: file could not be opened"<<endl;
exit(1);
}
string line;
vector<string> col1;
vector<double> col2;
vector<double> col3;
while (getline(inputFile, line))
{
if(not line.empty()){
auto lineData = split(line, ','); //separator can change in your case
col1.emplace_back(lineData[0]);
col2.emplace_back(std::stof(lineData[1]));
col3.emplace_back(std::stof(lineData[2]));
}
}
for(int i =0; i<(int) col1.size();i++) //printing the data;
cout<<col1[i]<<"\t"<<col2[i]<<"\t"<<col3[i]<<"\n";
return 0;
}
understand the above logic through the following approach:
read each line of the file.
for each line we will separate the column data through the
split(string, sep)
function which will return avector<string>
containing data of the row. Heresep
is the separator used in the file; as I made input file comma-separated, I used','
converting the returned
vector<string>
type row-data into appropriate data type and storing in respective column vectorcol1, col2, col3
.reference of split() functionality.
for another column that may have some missing data
you can add some logic like
if(lineData.size() > 3)
col4.emplace_back(std::stof(lineData[3]));
else
col4.emplace_back(0.0);
after col3.emplace_back(std::stof(lineData[2]));
line.
(c++) Reading numeric data in a column from a txt file and determining highest value
If you have the option of using the file as an input, then you could use simple cin in order to get your values for Time,Volt and Amp. ( the only thing you need to keep in mind is to ignore first row because they are just names)
If you know that all three values in each row will be present, then you can create while loop that runs until EOF. Then you read 3 values (Time, Volt, Amp) and compare with the previous Volt.
If previous volt is larger - ignore this row and move on.
Else - keep current Time, Volt and Amp.
On the next iteration, compare new 3 values to the max value of Volt so far.
Here is my "quick and dirty" solution:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// cin>>temp goes through names and ignores it since we don't need it
string temp;
cin >> temp;
cin >> temp;
cin >> temp;
float timeval = 0;
float volt = 0;
float amp = 0;
float timevalTemp = 0;
float voltTemp = 0;
float ampTemp = 0;
while(cin >> timevalTemp >> voltTemp >> ampTemp)
{
if(voltTemp > volt)
{
timeval = timevalTemp;
volt = voltTemp;
amp = ampTemp;
}
}
cout << "Max Time: " << timeval << endl;
cout << "Max Volt: " << volt << endl;
cout << "Max Amp: "<< amp << endl;
return 0;
}
Let me know if something is not clear. I ran it on your text file and it produces:
Max Time: 0.00035
Max Volt: 9.78167
Max Amp: 0.1473
Reading numbers from a text file with letters and whitespace
Assuming that your goal is not to retain the accuracy of the double
values in the file, one way to do this is to read the line in as a string, and remove any characters that are not digits, except whitespace and the .
.
Once you do that, then it's very simple using std::istringstream
to output the values:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
int main()
{
std::string line;
// Read the entire line
while (std::getline(std::cin, line))
{
// erase all non-digits, except for whitespace and the '.'
line.erase(std::remove_if(line.begin(), line.end(),
[](char ch) { return !std::isdigit(ch) && !std::isspace(ch) && ch != '.'; }), line.end());
// Now use the resulting line and read in the values
std::istringstream strm(line);
double oneValue;
while (strm >> oneValue)
std::cout << oneValue << " ";
}
}
Output:
87 98.5 4 9 0 94.3 98.4 84
Live Example
Related Topics
Why Do We Use Volatile Keyword
Advantages of Auto in Template Parameters in C++17
How to Create Cartesian Product of Vector of Vectors
The Written Versions of the Logical Operators
Why Can't Simple Initialize (With Braces) 2D Std::Array
What's the Scope of Inline Friend Functions
When Should I Use C++ Private Inheritance
How Does Delete[] Know It's an Array
Programmatically Create Static Arrays At Compile Time in C++
Static Member Initialization in a Class Template
Compiling a C++ Program With Gcc
Is 0 a Decimal Literal or an Octal Literal
Uses For Multiple Levels of Pointer Dereferences
Calling a Python Method from C/C++, and Extracting Its Return Value