我是编程新手。我有一个tcms软件,可以将所有数据导出到.txt
文件中。我想在c ++控制台上输出.txt
文件(与.txt
文件中的完全相同)但我能做的就是这个。谁能帮我?这是我的代码:
#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();
}
TEXT1.txt
(和我想要的输出)是
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
但我得到像这样的输出
WLC013
SIN LEI CHADMIN DEPA
0
0.00
0.00
0.00
0.00
2.00
WLC008
NAI SOO CHADMIN DEPA
...
是否可以编辑文本文件并为每个列添加标题? 谢谢!
答案 0 :(得分:2)
您正在逐字读取文件,需要逐行读取,以获得所需的输出。
while (getline(inFile,x)) {
cout << x << endl ;
}
要添加标题/标题或更好的格式,请参阅setw
在控制台上输出它,然后您只需将输出重定向>
用于文件。
假设您的来源名称为test.cpp
./test > new_file.txt
(linux)
或
test.exe > new_file.txt
(windows)
这是最简单的方法。还有其他方法。
答案 1 :(得分:0)
#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;
}