将.txt文件中的文本输出到c++控制台中

output text in .txt file into c++ console

本文关键字:c++ 控制台 输出 txt 文件 文本      更新时间:2023-10-16

我是编程新手。我有一个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(以及所需的输出i)是

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        
...

是否可以编辑文本文件并为每一列添加标题?非常感谢。

您正在逐字逐句地读取文件,需要逐行读取,以获得所需的输出。

while (getline(inFile,x)) {
cout << x << endl ;
}

要添加标题/标题或更好的格式,请参阅setw

在控制台上输出它,然后您可以简单地使用输出重定向>到一个文件。

假设您的源名称为test.cpp

./test > new_file.txt(linux)

test.exe > new_file.txt(窗口)

这是一种最简单的方法。也可以有其他方式。

#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 createdn";
    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;
 }