How to put numbers from txt file into vector in c++ - c++

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;
}

Related

I am trying to return an array sorted in descending order, Is there a reason my code is returning no output to the output file?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
ofstream outputFile;
string filename;
const int SIZE = 20;
float numbers[SIZE];
int i = 0;
float temp;
cin >> filename;
// Open files and if input file is not open return error message and end program
outputFile.open("output.txt");
inputFile.open(filename);
if (!inputFile)
{
cout << "File not found" << endl;
return -1;
}
// Get numbers from input file and sort them from largest to smallest
while (inputFile >> numbers[i])
{
i++;
}
for (i = 0; i < sizeof(numbers); i++)
{
if (numbers[i] < numbers[i + 1])
{
temp = numbers[i];
numbers[i + 1] = numbers[i];
numbers[i] = temp;
}
}
// Take numbers in new order and output them to output file
for (i = 0; i < sizeof(numbers); i++)
outputFile << numbers[i] << ", ";
// Close all files
outputFile.close();
inputFile.close();
return 0;
}
Write a program that opens a text file to load a sequence of real values, separated by commas and whitespaces. You can safely assume that the number of real values in all the files is less than or equal to 20. The program then sorts these values in the descending order, and outputs the sorted numbers to another text file. The user only enters the input file. This is the problem I am trying to solve.
Using modern C++ features makes this much easier than fixed size arrays and keeping track of how many items you've read in.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::ifstream in_file;
std::ofstream out_file;
const std::size_t SIZE = 0;
std::vector<float> numbers;
std::string in_file_name;
std::cin >> in_file_name;
in_file.open(in_file_name);
if (!in_file) {
std::cerr << "File not found" << std::endl;
return -1;
}
std::copy(std::istream_iterator<float>(in_file),
std::istream_iterator<float>(),
std::back_inserter(numbers));
in_file.close();
std::sort(numbers.begin(), numbers.end());
out_file.open("output.txt");
std::copy(numbers.begin(),
numbers.end(),
std::ostream_iterator<float>(out_file, ", "));
out_file.close();
return 0;
}

C++ print first ten lines in a file

I have this code but every time I run it,it only prints 11(the number of words in the array) over and over again when the amount of words is over 10. When the amount of words is under 10, nothing prints. Please help
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string word;
fstream file;
int count = 1;
file.open("file.txt");
int numOfLines=0;
while(!file.eof())
{
getline(file,word);
numOfLines++;
}
if(numOfLines<10)
{
while(!file.eof())
{
getline(file,word);
cout << word << endl;
count++;
}
cout << "The entire file has been displayed";
}
else
{
for(int i=0; i<10;i++)
{
cout << word << endl;
}
}
}
To read and print the first ten lines in a file:
#include <iostream>
#include <fstream>
int main()
{
std::string word;
std::fstream file;
file.open("file.txt");
if(!file.is_open())
return -1;
int numOfLines = 0;
while(getline(file, word) && numOfLines < 10){
std::cout << word << std::endl;
numOfLines++;
}
}
Live sample
Note that I removed using namespace std; it' s not a good practice, more in Why is "using namespace std;" considered bad practice?

Inserting integers from a text file to an integer array

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;
}

How do I remove all the punctuation from the file that I am reading from?

This is my main method in a file called main.cpp:
#include <iostream>
#include "ReadWords.h"
#include "Writer.h"
#include <cctype>
#include <string>
using namespace std;
int main() {
int count;
int length;
string word;
cout << "Please enter a filename: " << flush;
char filename[30];
cin >> filename;
This is where I am trying to delete all the punctuation in the file. Currently I am able to read the file and print all the values. I am struggling to access the file and delete the punctuation. I know that I am to use ispunct. I have tried many different implementations but cannot get it to work. How do I delete all the punctuation in the file?
ReadWords reader(filename);
while (reader.isNextWord()){
count = count + 1;
reader.getNextWord();
}
cout << "There are: " << count << " words in this text file" << endl;
return 0;
}
This is another file called ReadWords where I have all my method declarations: I don't think this is relevant/needed
#include "ReadWords.h"
#include <cstring>
#include <iostream>
using namespace std;
void ReadWords::close(){
}
ReadWords::ReadWords(const char *filename) {
//storing user input to use as the filename
//string filename;
wordfile.open(filename);
if (!wordfile) {
cout << "could not open " << filename << endl;
exit(1);
}
}
string ReadWords::getNextWord() {
string n;
if(isNextWord()){
wordfile >> n;
return n;
}
}
bool ReadWords::isNextWord() {
if (wordfile.eof()) {
return false;
}
return true;
}
Read from the input file one character at a time.
For each character you read:
If the character is not punctuation, write it to the output file.
If the character is punctuation, don't write it to the output file.

How to open any input file whether it contains words or numbers and prints it out. C++

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;