Why is the number of lines always 0? It should be 10, but the output is always 0.Is anything wrong with the method?
int main() {
vector<double> doubleCoefficient; // vector to store unknown number of equations (double)
/* Read from file and assign values to vector */
//File stream object
ifstream inputFile;
//Open the txt file
inputFile.open("test.txt");
//search for the text file
if(!inputFile.is_open())
{
cerr << "Error opening file \n";
exit(EXIT_FAILURE);
}
else
{
cout << "File found and successfully opened. \n";
}
double x;
while(!inputFile.eof()){
inputFile >> x;
doubleCoefficient.push_back(x);
}
int count =0;
string line;
while (getline(inputFile, line)){
count++;
}
cout << "Number of lines in text file:" << count << endl;
inputFile.close();
}
With while(!inputFile.eof()) You go to the end of the file, so after that, You cann't read lines.
You need to go back to the start using fseek()
try
fseek ( inputFile , 0 , SEEK_SET );
before counting the lines.
Related
I am new to C++ (I usually use Java) and am trying to make a k-ary heap. I want to insert values from a file into the heap; however, I am at a loss with the code for the things I want to do.
I wanted to use .nextLine and .hasNextLine like I would in Java with a scanner, but I am not sure those are applicable to C++. Also, in the file the items are listed as such: "IN 890", "IN 9228", "EX", "IN 847", etc. The "IN" portion tells me to insert and the "EX" portion is for my extract_min. I don't know how to separate the string and integer in C++ so I can insert just the number though.
int main(){
BinaryMinHeap h;
string str ("IN");
string str ("EX");
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> x) {
sum = sum + x;
if(str.find(nextLin) == true //if "IN" is in line)
{
h.insertKey(nextLin); //insert the number
}
else //if "EX" is in line perform extract min
}
inFile.close();
cout << "Sum = " << sum << endl;
}
The result should just add the number into the heap or extract the min.
Look at the various std::istream implementations - std::ifstream, std::istringstream, etc. You can call std::getline() in a loop to read a std::ifstream line by line, using std::istringstream to parse each line. For example:
int main() {
BinaryMinHeap h;
string line, item;
int x sum = 0;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
return 1; // terminate with error
}
while (getline(inFile, line)) {
istringstream iss(line);
iss >> item;
if (item == "IN") {
iss >> x;
sum += x;
h.insertKey(x);
}
else if (item == "EX") {
// perform extract min
}
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}
I am trying to figure out how to sum the values generated from a random number generator.
Below my code writes the random number and reads it, and outputs all the random numbers.
I simply cannot figure out how to sum the values generated from the random number.
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
class Array
{
public:
void Arrayoutput()
{
string array[1000]; // creates array to hold names
short loop=0; //short for loop for input
string line; //this will contain the data read from the file
ifstream myfile ("Asg4.txt"); //opening the file.
if (myfile.is_open()) //if the file is open
{
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop]= line;
cout << array[loop] << endl; //and output it
loop++;
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
}
};
int main()
{
Array Array1;
ofstream myfile;
myfile.open ("Asg4.txt");
for (int i = 0; i < 1000; i++) //random number generator
{
myfile << 1+(rand()%1000) << endl;
}
myfile.close();
Array1.Arrayoutput();
return 0;
}
Here's how to read numbers from a file and add them up
ifstream myfile ("Asg4.txt"); //opening the file.
int total = 0;
int number;
while (myfile >> number)
total += number;
cout << "The total is " << total << "n";
I'm having trouble figuring out how to read a file line by line into different data type vectors. Is there a way to do this with inFile >> ? My code is below. Thanks in advance!
void fileOpen()
{
fstream inFile;
inFile.open(userFile);
// Check if file open successful -- if so, process
if (!inFile.is_open()) {cout << "File could not be opened.";}
else
{
cout << "File is open.\n";
string firstLine;
string line;
vector<char> printMethod;
vector<string> shirtColor;
vector<string> orderID;
vector<string> region;
vector<int> charCount;
vector<int> numMedium;
vector<int> numLarge;
vector<int> numXL;
getline(inFile, firstLine); // get column headings out of the way
cout << firstLine << endl << endl;
while(inFile.good()) // while we are not at the end of the file, process
{
while(getline(inFile, line)) // get each line of the file separately
{
for (int i = 1; i < 50; i++)
{
inFile >> date >> printMethod.at(i);
cout << date << printMethod.at(i) << endl;
}
}
}
}
}
Before you use vector.at(i) in your case you should be sure that your vector is long enough cause at will generate out of range exception. As I can see from your code your vector printMethod contains no more than 50 elements so you can resize vector printMethod before use e.g.
vector<char> printMethod(50);
or
vector<char> printMethod;
printMethod.resize(50);
If you're planning to use a variable number of elements more than 50 you should use push_back method like #Phil1970 recommended e.g.
char other_data;
inFile >> date >> other_data;
printMethod.push_back(other_data);
I want to make a factory class which creates and loads objects in from a file;
however when I try to read in a int from the file it appears to return a incorrect number.
std::ifstream input;
input.open("input.txt");
if (!input.is_open()){
exit(-1);
}
int number;
input >> number;
cout << number;
input.close();
When I enter a number in the input.txt file it shows: -858993460.
Changing the number doesn’t make a difference and when I use cin instead of ifstream it works like it should. I'm probably just missing something really stupid, but I can't figure it out.
Edit: Using getLine() works like it should. I guess there is a problem using >>.
Here is another solution to open a file a read it line by line:
string line;
ifstream myfile("input.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n'; // Use this to verify that the number is outputed
// Here you can transform your line into an int:
// number = std::stoi(line);
}
// myfile.close(); Use this if you want to handle the errors
}
else cout << "Unable to open file";
If you don't want to read line by line, just remove the while
...
getline(myfile,line);
number = std::stoi(line);
...
Read multiple numbers in one line
Image that your input file is like this:
1, 2.3, 123, 11
1, 2
0.9, 90
Then, you can use this piece of code to read all the numbers:
string line;
ifstream myfile("input.txt");
string delimiter = ", ";
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << "Reading a new line: " << endl;
size_t pos = 0;
string token;
while ((pos = line.find(delimiter)) != string::npos) {
token = line.substr(0, pos);
cout << token << endl; // Instead of cout, you can transform it into an int
line.erase(0, pos + delimiter.length());
}
}
}
else cout << "Unable to open file";
The output will be:
Reading a new line:
1
2.3
123
11
Reading a new line:
1
2
Reading a new line:
0.9
90
New solution that may work =)
I didn't test this, but it works apparently:
std::ifstream input;
double val1, val2, val3;
input.open ("input.txt", std::ifstream::in);
if (input >> val1 >> val2 >> val3) {
cout << val1 << ", " << val2 << ", " << val3 << endl;
}
else
{
std::cerr << "Failed to read values from the file!\n";
throw std::runtime_error("Invalid input file");
}
To check the IO, see http://kayari.org/cxx/yunocheckio.html
I am trying to debugg this, but can't figure out the issue here. Why is it saying no matching function for a call to naiveGaussianElimination evnthough i have passed the correct parameters?
void naiveGaussianElimination(int count,float doubleCoefficient[][count+1]) {
}
int main() {
/*
Read from file and assign values to vector
*/
//File stream object
ifstream inputFile;
// store file name
string fileName;
// ask user for the file name and store it
cout << "Enter the file name:>> ";
cin >> fileName;
//Open the txt file
inputFile.open(fileName.c_str());
//search for the text file
if(!inputFile.is_open())
{
cerr << "Error opening file \n";
exit(EXIT_FAILURE);
}
else
{
cout << "File found and successfully opened. \n";
}
/*
find the number of variables in the equation
*/
int count =0;
string line;
while (getline(inputFile, line)){
count++;
}
cout << "Number of variables: " << count << endl; // show total variables in text file
// clear the eof flag and set it to top
inputFile.clear();
inputFile.seekg (0, ios::beg);
// 2D array to store augmented matrix
float doubleCoefficient [count][count+1];
naiveGaussianElimination(count,doubleCoefficient);
inputFile.close();
}
**Use dynamic array for
//2D dynamic array to store augmented matrix**
float **doubleCoefficient = new float*[count];
for (int i=0; i<(count+1); i++) {
doubleCoefficient[i] = new float[count+1];
}
}