I have a text file filled with some integers and I want to insert these numbers to an integer array from this text file.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file("numbers.txt");
int nums[1000];
if(file.is_open()){
for(int i = 0; i < 1000; ++i)
{
file >> nums[i];
}
}
return 0;
}
And, my text file contains integers line by line like:
102
220
22
123
68
When I try printing the array with a single loop, it prints lots of "0" in addition to the integers inside the text file.
Always check the result of text formatted extraction:
if(!(file >> insertion[i])) {
std::cout "Error in file.\n";
}
Can it be the problem is your text file doesn't contain 1000 numbers?
I'd recommend to use a std::vector<int> instead of a fixed sized array:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main(){
ifstream file("numbers.txt");
std::vector<int> nums;
if(file.is_open()){
int num;
while(file >> num) {
nums.push_back(num);
}
}
for(auto num : nums) {
std::cout << num << " ";
}
return 0;
}
Related
I must say I'm completely new to C++. I got the following problem.
I've got a text file which only has one 8 digits number
Text-File: "01485052"
I want to read the file and put all numbers into a vector, e.g. Vector v = ( 0, 1, 4, 8, 5, 0, 5, 2 ). Then write it into another text file.
How do I implement it the best way? That's what I made possible so far:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char matrikelnummer[100];
cout << "Enter file name: ";
cin >> matrikelnummer;
// Declare input file stream variable
ifstream inputFile(matrikelnummer);
string numbers;
//Check if exists and then open the file
if (inputFile.good()) {
//
while (getline(inputFile, numbers))
{
cout << numbers;
}
// Close the file
inputFile.close();
}
else // In case TXT file does not exist
{
cout << "Error! This file does not exist.";
exit(0);
return 0;
}
// Writing solutions into TXT file called Matrikelnummer_solution.txt
ofstream myFile;
myFile.open("Matrikelnummer_solution.txt");
myFile << "Matrikelnummer: " << numbers << '\n';
myFile.close();
return 0;
}
You can use the following program for writing the number into another file and also into a vector:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream inputFile("input.txt");
std::string numberString;
int individualNumber;
std::vector<int> vec;
if(inputFile)
{
std::ofstream outputFile("outputFile.txt");
while(std::getline(inputFile, numberString,'\n'))//go line by line
{
for(int i = 0; i < numberString.size(); ++i)//go character by character
{
individualNumber = numberString.at(i) - '0';
outputFile << individualNumber;//write individualNumber into the output file
vec.push_back(individualNumber);//add individualNumber into the vector
}
}
outputFile.close();
}
else
{
std::cout<<"input file cannot be openede"<<std::endl;
}
inputFile.close();
//print out the vector
for(int elem: vec)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the above program can be seen here.
Read from file to numbers using inputFile >> numbers. Then, add each digit character of the string to a std::vector.
Also, to write to the file, write each element of vector in a for loop.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
char matrikelnummer[100];
cout << "Enter file name: \n";
cin >> matrikelnummer;
// Declare input file stream variable
ifstream inputFile(matrikelnummer);
string numbers;
vector<int> individualNumbers;
//Check if exists and then open the file
if (inputFile.good()) {
inputFile >> numbers;
for (int i = 0; i < numbers.length(); i++) {
if (numbers[i] >= '0' && numbers[i] <= '9')
individualNumbers.push_back(numbers[i] - '0');
}
// Close the file
inputFile.close();
}
else // In case TXT file does not exist
{
cout << "Error! This file does not exist.";
exit(0);
return 0;
}
// Writing solutions into TXT file called Matrikelnummer_solution.txt
ofstream myFile;
myFile.open("Matrikelnummer_solution.txt");
myFile << "Matrikelnummer: ";
for (int number : individualNumbers) {
myFile << number << " ";
}
myFile << endl;
myFile.close();
return 0;
}
Making a program that reads integers from a file and creates an array, I have that part completed however I am trying to figure out how to change the SIZE value depending on how many ints are in the file. This file has 15 integers but another file may have more and this array will not take in all the ints.
using namespace std;
const int SIZE = 15;
int intArray[SIZE];
void readData(istream& inFile) {
for (int i = 0; i < SIZE; i++){
inFile >> intArray[i];
cout << intArray[i] << " ";
}
}
int main() {
ifstream inFile;
string inFileName = "intValues.txt";
inFile.open(inFileName.c_str());
int value, count = 0;
while(inFile >> value){
count += 1;
}
cout << count;
readData(inFile);
return 0;
}
As you can see I have a while loop counting the number of ints in the file however when I assign that to the size value I was running into many different issues.
A fixed-sized array simply cannot be resized, period. If you need an array whose size can change at runtime, use std::vector instead.
More importantly, you are reading through the entire file just to count the number of integers, and then you are trying to read the values from where the previous loop left off. You are not seeking the ifstream back to the beginning of the file so you can re-read what you have already read.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
int value, count = 0;
while (inFile >> value){
++count;
}
cout << count;
std::vector<int> intArray;
intArray.reserve(count);
inFile.seekg(0);
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
return 0;
}
Alternatively, don't even bother counting the integers, just let the std::vector grow as needed, eg:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
vector<int> intArray;
int value;
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
// you an get the count from intArray.size()
return 0;
}
I am having difficulty populating an array from a .txt file. I can do it without the while loop if I already know the size of the file. However, once I incorporate a while loop to extract the file size the input odes not configure correctly. Pleas take a look over my code an let me know if you see where I am going wrong.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
int main()
{
using namespace std;
const char *inName_1 = "Instance_1.txt";
const char *inName_2 = "Instance_2.txt";
int arraySize_1 = 0, arraySize_2 = 0;
int array_1[20];
int array_2[20];
int number;
ifstream A2_file_1(inName_1);
if (A2_file_1.fail())
{
cout << "File 1 not open!" << '\n';
}
while (!A2_file_1.eof())
{
arraySize_1++;
A2_file_1 >> number;
}
if (A2_file_1.is_open())
{
for (int i = 0; i < arraySize_1; i++)
{
A2_file_1 >> array_1[i];
}
A2_file_1.close();
}
cout << "The size of the array 1 is: " << arraySize_1 << endl;
for (int i = 0; i < arraySize_1; i++)
{
cout << array_1[i] << endl;
}
return 0;
}
To read an arbitrary amount of numeric values from a text-file, all you need is an std::vector and a couple of std::istreambuf_iterator objects.
Then is as simple as
std::ifstream input("Instance_1.txt");
std::vector<int> values(std::istreambuf_iterator<int>(input),
std::istreambuf_iterator<int>());
That's it. Those four lines of code (counting the empty line) will read all int values from the text file Instance_1.txt and place them into the vector values.
The file is a text file named TotalMonthlyRainfall2014.txt and it contains the following in a single line:
0.33 0.41 1.45 1.74 3.40 3.26 0.98 4.34 0.06 2.09 2.13 1.13
I want to read the numbers from the file and store them into a single array called monthRain. so monthRain[0] will be 0.33, monthRain[1] will be 0.41, and so forth.
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
//global variable
const int months = 12;
const string FILENAME = "TotalMonthlyRainfall2014.txt";
int main()
{
ifstream inFile; //input file stream
float monthRain[months];
//open the file
inFile.open(fileName.c_str());
//loop through and get data from file
for (int i = 0; i < months && (inFile >> monthRain); i++)
{
cout << setprecision(2) << fixed << showpoint << monthRain[i];
}
inFile.close();
}
I guess the question is how to properly store the numbers into array monthRain.
This should fix your problem. It will parse all rows and place each line in a string stream. It then parses the string stream and streams the elements into doubles. It should work for any combination of rows and column elements.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main(){
// Open file
ifstream fileStream;
fileStream.open("myIniFile.txt");
// Initialize variables
string lineString;
int counter=0;
vector<vector<double> > myData; // Matrix which holds all data
vector<double> myLine; // Temporary vector to hold each row
double currentNumber;
// Read file
while(!fileStream.eof()){
++counter;
getline(fileStream,lineString); // Stream this line in a string
if (lineString!=""){ // If empty, exit
cout<<"Line #"<<counter<<" : "; // Print
cout<<lineString<<endl; // output
stringstream myS_stream(lineString);
while(myS_stream>>currentNumber){ // Important as a simple break condition will read the last element twice
cout<<"\tFound double number in string stream : "<< currentNumber<<endl;
myLine.push_back(currentNumber);
}
myData.push_back(myLine);
myLine.clear();
}
}
fileStream.close(); // Close file
// Print your data
cout<<"\nMy data is : "<<endl;
for (auto row : myData){
cout<<"\t";
for (auto element : row){
cout<<" "<<element;
}
cout<<endl;
}
// Convert to the format you want, but I suggest using std::vector
// if you can help it
double *monthRain = &myData.at(0)[0];
return 0;
}
// Headers
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// Global variables
const int months = 12;
const string FILENAME = "TotalMonthlyRainfall2014.txt";
int main()
{
ifstream inFile; //input file stream
float monthRain[months];
//open the file
inFile.open(FILENAME.c_str());
//loop through and get data from file
for (int i = 0; i < months && (inFile >> monthRain[i]); i++)
{
cout << setprecision(2) << fixed << showpoint << monthRain[0] << '\n';
}
inFile.close();
}
Progress! Now whenever 0 is in:
cout << setprecision(2) << fixed << showpoint << monthRain[0] << '\n';
it outputs 0.33 which is correct, but it outputs it 12 times.
So Lets say this is what the input file contains
12
Hello
45
54
100
Cheese
23
How would I print it out on the screen in that order.
This is what I had but it skips some lines.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
I suggest using www.cplusplus.com to answer these questions.
However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;