Reputation: 1
I'm new in programming. I had a tcms software which can export all the data into .txt
file. I want to output the .txt
file on c++ console (exactly the same as in the .txt
file) But all I can do is this. Can anyone help me? Here's my code:
#include <iostream>
#include <iomanip>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
string x;
ifstream inFile;
inFile.open("TEXT1.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> x) {
cout << x << endl ;
}
inFile.close();
}
The TEXT1.txt
(and the output i desired) is
WLC013 SIN LEI CHADMIN DEPA 0 0.00 0.00 0.00 0.00 2.00
WLC008 NAI SOO CHADMIN DEPA 0 0.00 0.00 0.00 0.00 2.00
WLC017 SYLVESTER ADMIN DEPA 0 0.00 0.00 0.00 0.00 2.00
WLC004 CHANG KUEIADMIN DEPA 0 0.00 0.00 0.00 0.00 2.00
But I get output like this
WLC013
SIN LEI CHADMIN DEPA
0
0.00
0.00
0.00
0.00
2.00
WLC008
NAI SOO CHADMIN DEPA
...
And is it possible to edit the text file and add in the title for each of the column? Thank you!
Upvotes: 0
Views: 19934
Reputation: 1
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
int main()
{
char directory[_MAX_PATH + 1];
char filename[_MAX_PATH + 1];
std::cout << "Please provide a directory Path: ";
std::cin.getline(directory, _MAX_PATH);
std::cout << "\nPlease provide a name for file: ";
std::cin.getline(filename, _MAX_PATH);
strcat(directory, filename);
std::ofstream file_out(directory);
if (!file_out) {
std::cout << "Could not open.";
return -1;
}
std::cout << directory << "Was created\n";
for (int i = 0; i <= 5; ++i) {
std::cout << "(Press ENTER to EXIT): Please enter a line of text you
would like placed, in the document: ";
char nest[100], *p;
std::cin.getline(nest, _MAX_PATH);
p = strtok(nest, "\n|\t|\r");
while (p != nullptr) {
p = strtok(nullptr, " ");
std::cout << " The line (";
file_out << nest << std::endl;
std::cout << " )Line was successfully added.\n";
}
}
file_out.close();
return 0;
}
Upvotes: 0
Reputation: 47794
You're reading the file word by word, you need to read line by line, to get desired output.
while (getline(inFile,x)) {
cout << x << endl ;
}
For adding title/header or better formatting see setw
Output it on console and then you can simply use output redirection >
to a file.
Say you source name is test.cpp
./test > new_file.txt
(linux)
or
test.exe > new_file.txt
(windows)
This is a simplest approach. There can be other ways too.
Upvotes: 2